Retrieve all values from HashMap keys in an ArrayList Java

前端 未结 9 1375
野性不改
野性不改 2021-01-31 14:21

Good day, this is kind of confusing me now(brain freeze!) and seem to be missing something. Have an ArrayList which i populate with a HashMap. now i put in my HashMap and arrayl

9条回答
  •  清酒与你
    2021-01-31 15:07

    Why do you want to re-invent the wheel, when you already have something to do your work. Map.keySet() method gives you a Set of all the keys in the Map.

    Map map = new HashMap();
    
    for (String key: map.keySet()) {
        System.out.println("key : " + key);
        System.out.println("value : " + map.get(key));
    }
    

    Also, your 1st for-loop looks odd to me: -

       for(int k = 0; k < list.size(); k++){
                map = (HashMap)list.get(k);
       }
    

    You are iterating over your list, and assigning each element to the same reference - map, which will overwrite all the previous values.. All you will be having is the last map in your list.

    EDIT: -

    You can also use entrySet if you want both key and value for your map. That would be better bet for you: -

        Map map = new HashMap();
    
        for(Entry entry: map.entrySet()) {
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }
    

    P.S.: -
    Your code looks jumbled to me. I would suggest, keep that code aside, and think about your design one more time. For now, as the code stands, it is very difficult to understand what its trying to do.

提交回复
热议问题