Java 8 introduced forEach method to iterate over the collections and Streams in Java. It is defined in Iterable and Stream interface. It is a default method defined in the Iterable interface. Collection classes which extends Iterable interface can use forEach loop to iterate elements.
Java 8 forEach example
package com.w3spoint;
import java.util.HashMap;
import java.util.Map;
public class Test{
public static void main(String[] args) {
Map<Integer, String> hashMap = new HashMap<Integer, String>();
hashMap.put(1, "Jai");
hashMap.put(2, "Mahesh");
hashMap.put(3, "Vishal");
hashMap.put(4, "Vivek");
hashMap.put(5, "Hemant");
hashMap.put(6, "Naren");
//forEach to iterate and display each key and value pair
hashMap.forEach((key,value)->System.out.println(key+" - "+value));
}
} |
package com.w3spoint; import java.util.HashMap;
import java.util.Map; public class Test{
public static void main(String[] args) {
Map<Integer, String> hashMap = new HashMap<Integer, String>();
hashMap.put(1, "Jai");
hashMap.put(2, "Mahesh");
hashMap.put(3, "Vishal");
hashMap.put(4, "Vivek");
hashMap.put(5, "Hemant");
hashMap.put(6, "Naren");
//forEach to iterate and display each key and value pair
hashMap.forEach((key,value)->System.out.println(key+" - "+value));
}
}
Output
1 - Jai
2 - Mahesh
3 - Vishal
4 - Vivek
5 - Hemant
6 - Naren |
1 - Jai
2 - Mahesh
3 - Vishal
4 - Vivek
5 - Hemant
6 - Naren