java hashmap key iteration

前端 未结 7 649
谎友^
谎友^ 2020-12-29 06:46

Is there any way to iterate through a java Hashmap and print out all the values for every key that is a part of the Hashmap?

相关标签:
7条回答
  • 2020-12-29 06:55

    Java 8 added Map.forEach which you can use like this:

    map.forEach((k, v) -> System.out.println("key=" + k + " value=" + v));
    

    There's also replaceAll if you want to update the values:

    map.replaceAll((k, v) -> {
        int newValue = v + 1;
        System.out.println("key=" + k + " value=" + v + " new value=" + newValue);
        return newValue;
    });
    
    0 讨论(0)
  • 2020-12-29 07:01
    for (Map.Entry<T,U> e : map.entrySet())
    {
        T key = e.getKey();
        U value = e.getValue();
        .
        .
        .
    }
    

    In addition, if you use a LinkedHashMap as the implementation, you'll iterate in the order the key/value pairs were inserted. If that's not important, use a HashMap.

    0 讨论(0)
  • 2020-12-29 07:08
    public class abcd {
        public static void main(String[] args)
        {
           Map<Integer, String> testMap = new HashMap<Integer, String>();
            testMap.put(10, "a");
            testMap.put(20, "b");
            testMap.put(30, "c");
            testMap.put(40, "d");
            for (Entry<Integer, String> entry : testMap.entrySet()) {
                Integer key=entry.getKey();
                String value=entry.getValue();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-29 07:09

    Yes, you do this by getting the entrySet() of the map. For example:

    Map<String, Object> map = new HashMap<String, Object>();
    
    // ...
    
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
    }
    

    (Ofcourse, replace String and Object with the types that your particular Map has - the code above is just an example).

    0 讨论(0)
  • 2020-12-29 07:14

    Keep it simple, please:

    HashMap<String,String> HeyHoLetsGo = new HashMap();
    
    HeyHoLetsGo.put("I", "wanna be your dog");
    HeyHoLetsGo.put("Sheena", "is a punk rocker");
    HeyHoLetsGo.put("Rudie", "can't fail");
    
    for ( String theKey : HeyHoLetsGo.keySet() ){
        System.out.println(theKey + " "+HeyHoLetsGo.get(theKey));
    }
    
    0 讨论(0)
  • 2020-12-29 07:15
    hashmap.keySet().iterator()
    

    use a for loop to iterate it.

    then use hashmap.get(item) to get individual values,

    Alternatively just use entrySet() for getting an iterator for values.

    0 讨论(0)
提交回复
热议问题