271
Java forEach loop
Java provides a new method forEach() to iterate the elements. 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.
This method takes a single parameter which is a functional interface. So, you can pass lambda expression as an argument.
forEach() Signature in Iterable Interface
Java 8 forEach() example 1
Output:
------------Iterating by passing lambda expression-------------- Football Cricket Chess Hocky
Java 8 forEach() example 2
Output:
------------Iterating by passing method reference--------------- Football Cricket Chess Hocky
Java Stream forEachOrdered() Method
Along with forEach() method, Java provides one more method forEachOrdered(). It is used to iterate elements in the order specified by the stream.
Singnature:
Java Stream forEachOrdered() Method Example
Output:
------------Iterating by passing lambda expression--------------- Football Cricket Chess Hocky ------------Iterating by passing method reference--------------- Football Cricket Chess Hocky
Next TopicJava 8 Collectors