|
|
Java 8 - forEach method example with Map
forEach is a new method introduced in Java 8 to iterate over collections. Here is an example on forEach method
to iterate over Map.
package com.java2novice.java8;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class ForEachMapEx {
public static void main(String a[]) {
Map<String, String> countryMap = new HashMap<>();
countryMap.put("India", "Delhi");
countryMap.put("USA", "Washington, D.C.");
countryMap.put("Japan", "Tokyo");
countryMap.put("Canada", "Ottawa");
// iterate through Map normal way
ForEachMapEx.iterateMap(countryMap);
// iterate through Map using forEach method
ForEachMapEx.iterateMapUsingForEach(countryMap);
}
public static void iterateMap(Map<String, String> countryMap) {
System.out.println("<----------Iterating in normal way------------->");
for(Entry<String, String> entry:countryMap.entrySet()) {
System.out.println("Country: "+entry.getKey()+" : Capital: "+entry.getValue());
}
}
public static void iterateMapUsingForEach(Map<String, String> countryMap) {
System.out.println("\n<----------Iterating using forEach method------------>");
countryMap.forEach((k,v)->System.out.println("Country: "+k+" : Capital: "+v));
countryMap.forEach((k,v)->{
// you can implement some business logic here..
});
}
}
|
|
Output: |
<----------Iterating in normal way------------->
Country: Canada : Capital: Ottawa
Country: USA : Capital: Washington, D.C.
Country: Japan : Capital: Tokyo
Country: India : Capital: Delhi
<----------Iterating using forEach method------------>
Country: Canada : Capital: Ottawa
Country: USA : Capital: Washington, D.C.
Country: Japan : Capital: Tokyo
Country: India : Capital: Delhi
|
|
|
|
|
Java 8 forEach method examples
- Java 8 forEach example with Map
- Java 8 forEach example with List
|
|
What is wrapper class?
Everything in java is an object, except primitives. Primitives are
int, short, long, boolean, etc. Since they are not objects, they cannot
return as objects, and collection of objects. To support this, java provides
wrapper classes to move primitives to objects. Some of the wrapper classes
are Integer, Long, Boolean, etc.
It is amazing what you can accomplish if you do not care who gets the credit.
-- Harry Truman
|