Retrieve all values from HashMap keys in an ArrayList Java

前端 未结 9 1377
野性不改
野性不改 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<String, Integer> map = new HashMap<String, Integer>();
    
    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<String, Integer> map = new HashMap<String, Integer>();
    
        for(Entry<String, Integer> 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.

    0 讨论(0)
  • 2021-01-31 15:07

    It has method to find all values from map:

    Map<K, V> map=getMapObjectFromXyz();
    Collection<V> vs= map.values();
         
    

    Iterate over vs to do some operation

    0 讨论(0)
  • 2021-01-31 15:11

    Java 8 solution for produce string like "key1: value1,key2: value2"

    private static String hashMapToString(HashMap<String, String> hashMap) {
    
        return hashMap.keySet().stream()
                .map((key) -> key + ": " + hashMap.get(key))
                .collect(Collectors.joining(","));
    
    }
    

    and produce a list simple collect as list

    private static List<String> hashMapToList(HashMap<String, String> hashMap) {
    
        return hashMap.keySet().stream()
                .map((key) -> key + ": " + hashMap.get(key))
                .collect(Collectors.toList());
    
    }
    
    0 讨论(0)
提交回复
热议问题