Looping Through a Map in Java

If you need to merge or add values to existing map, or may be perform some other operations for entire map you can use forEach lambda method.

For example let’s see how to add key-value pairs from one map to other:


Map<String, String> myMap = new LinkedHashMap<String, String>();
myMap.put("keyFromOriginalMap", "valueFromOriginalMap");

Map<String, String> anotherMap = new LinkedHashMap<>();

anotherMap.put("keyFromAnotherMap1", "valueFromAnotherMap1");
anotherMap.put("keyFromAnotherMap2", "valueFromAnotherMap2");
anotherMap.put("keyFromAnotherMap3", "valueFromAnotherMap3");

anotherMap.forEach((k, v) -> myMap.put(k.toString(), v.toString()));

myMap.forEach((k, v) -> System.out.println(k + " : " + v));

Output:

keyFromOriginalMap : valueFromOriginalMap
keyFromAnotherMap1 : valueFromAnotherMap1
keyFromAnotherMap2 : valueFromAnotherMap2
keyFromAnotherMap3 : valueFromAnotherMap3

Don’t forget that if the order of the elements is importing for you, then useĀ LinkedHashMap instead of regular HashMap.

Happy codding!

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.