- Iterate through Map using forEach method
- Iterate through Map's EntrySet using Iterator
- Iterate through Map's EntrySet using Enhanced for loop
forEach method in Map takes a java.util.function.BiConsumer as argument,
which is a functional interface tha you can pass as Lambda function.
A java.util.function.BiConsumer functional interface takes key,value pair as arguments.
public static void iterateUsingForEachLoop() {
Map<String, String> map = Map.of("Item 1","Tomatoes", "Item 2","Oranges");
map.forEach((key, value)->System.out.println("Key : "+ key + " , Value : "+value));
}
When you run above program, you will get the following output.
Key : Item 1 , Value : Tomatoes
Key : Item 2 , Value : Oranges
You can obtain EntrySet by calling entrySet() method on Map,
and obtain Iterator by calling iterator() on EntrySet.
public static void iterateViaEntrySetIterator() {
Map<String, String> map = Map.of("Item 1","Tomatoes", "Item 2","Oranges");
Iterator<Map.Entry<String, String>> ite = map.entrySet().iterator();
while(ite.hasNext()) {
Map.Entry<String, String> entry = ite.next();
System.out.println("Key : "+ entry.getKey() + " , Value : "+entry.getValue());
}
}
When you run above program, you will get the following output.
Key : Item 1 , Value : Tomatoes
Key : Item 2 , Value : Oranges
You can obtain EntrySet by calling entrySet() method on Map, and then you iterate through EntrySet.
public static void iterateViaEntrySetEnhancedForLoop() {
Map<String, String< map = Map.of("Item 1","Tomatoes", "Item 2","Oranges");
for(Map.Entry<String, String< entry: map.entrySet()) {
System.out.println("Key : "+ entry.getKey() + " , Value : "+entry.getValue());
}
}
When you run above program, you will get the following output.
Key : Item 1 , Value : Tomatoes
Key : Item 2 , Value : Oranges
Similar Articles
-
How to remove elements from a Map