Java 8 - Examples of the forEach loop

Java 8 provides additional features and new ways to perform the browsing. There are scenarios where these new concepts are more performant and recommended.

The majority of Java 8 features focus on lambda expressions, as well as related features such as flows, methods, and interfaces. Another feature in Java 8 is the forEach.

forEach() can be implemented to be faster than the for-each loop, in Java 8 the interface iterable uses the most optimized method for traversing elements as opposed to the standard method of traversing.

In this article, you'll learn how to iterate through a java.util.List and a java.util.Map with a new loop forEach of java 8.

forEach and java.util.Map

This code shows the usual way to browse a Map:

Map map = new HashMap< > (); 
map.put(1, "A");
map.put(2, "B");
map.put(3, "C");
map.put(4, "D");
map.put(5, "E");

for (Map.Entry entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue());
}
With Java 8, you can browse a Map with the forEach loop and lambda.

Map map = new HashMap< > (); 
map.put(1, "A");
map.put(2, "B");
map.put(3, "C");
map.put(4, "D");
map.put(5, "E");

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

items.forEach((k,v)->{
System.out.println("key: " + k + " Value: " + v);
if("D".equals(v)){
System.out.println("D");
}
});

forEach and java.util.List

This code example shows the usual browse with the for:

List arraylist = new ArrayList< > (); 
arraylist.add("A");
arraylist.add("B");
arraylist.add("C");
arraylist.add("D");
arraylist.add("E");
arraylist.add("F");

for(String val : arraylist){
System.out.println(val);
}
In Java 8, you can browse a List with forEach lambda expression or method reference.

List arraylist = new ArrayList< > (); 
arraylist.add("AB");
arraylist.add("BC");
arraylist.add("CD");
arraylist.add("DE");
arraylist.add("EF");
arraylist.add("FG");

//lambda
arraylist.forEach(item-> System.out.println(item));

arraylist.forEach(item->{
if("D".equals(item)){
System.out.println(item);
}
});

//method reference
arraylist.forEach(System.out::p rintln);

//Create a filter with stream()
//it should show CD output
arraylist.stream()
.filter(s-> s.contains("CD"))
.forEach(System.out::p rintln);
References:
Javadoc: Java 8 - forEach