java hashmap key iteration

Viewed 57133

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 Answers

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));
}

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;
});
Related