We can loop through a HashMap
in a number of different ways. In this shot, we will learn three common ways to loop a HashMap
.
forEach
methodThe forEach
method loops through all the entries of the HashMap
. The forEach
method takes the BiConsumer
Map
.
import java.util.HashMap;import java.util.function.BiConsumer;class LoopHashMapByForEach {public static void main(String[] args) {// create an HashMapHashMap<Integer, String> numbers = new HashMap<>();numbers.put(1, "One");numbers.put(2, "Two");numbers.put(3, "Three");numbers.forEach( (key, value) -> {System.out.println(key +" - " +value);});System.out.println("---------");System.out.println("Using Bi Consumer");BiConsumer<Integer, String> biConsumer = (key, value) -> System.out.println(key + " # " + value);numbers.forEach(biConsumer);}}
In the code above, we have created a HashMap
and used the forEach
method to loop the HashMap
. We passed a lambda
forEach
method. Then, we created a BiConsumer
forEach
method.
keySet
of HashMapThe keySet
method returns all the keys of the HashMap
as a Set
.
import java.util.HashMap;import java.util.Set;class LoopHashMapByForEach {public static void main(String[] args) {// create an HashMapHashMap<Integer, String> numbers = new HashMap<>();numbers.put(1, "One");numbers.put(2, "Two");numbers.put(3, "Three");Set<Integer> keys = numbers.keySet();for (Integer key: keys){System.out.println(key + " # " + numbers.get(key));}}}
In the code above, we used the keySet
method of the HashMap
to get all the keys
of the HashMap
, and looped all the keys to print values of all of them.
entrySet()
methodThe entrySet
method returns a Set
with key-value mappings as an Entry
.
import java.util.HashMap;import java.util.Map;import java.util.Set;import java.util.function.BiConsumer;class LoopHashMapByForEach {public static void main(String[] args) {// create an HashMapHashMap<Integer, String> numbers = new HashMap<>();numbers.put(1, "One");numbers.put(2, "Two");numbers.put(3, "Three");Set<Map.Entry<Integer, String>> entries = numbers.entrySet();for (Map.Entry<Integer, String> entry : entries) {Integer key = entry.getKey();String value = entry.getValue();System.out.println(key + " # " + value);}}}
In the code above, we used the entrySet()
method to get a Set
which contains all the mapping of the HashMap
. Then, we looped the entrySet
and printed the key and value.