forEach
Java provides a new method forEach() to iterate the elements. It is defined in the Iterable and Stream interface. It is a default method defined in the Iterable interface. Collection classes which extend Iterable interface can use the forEach loop to iterate elements
This method takes a single parameter which is a functional interface. So, you can pass a lambda expression as an argument.
forEach() Signature in Iterable Interface
default void forEach(Consumeraction)
import java.util.List; public class Example1 { public static void main(String[] args) { List
import java.util.ArrayList;gamesList = new ArrayList (); gamesList.add("Football"); gamesList.add("Cricket"); gamesList.add("Chess"); gamesList.add("Hocky"); System.out.println("Iterating by passing lambda expression"); gamesList.forEach(games -> System.out.println(games)); } } output Iterating by passing lambda expression Football Cricket Chess Hocky
Example2
import java.util.List; public class Example2 { public static void main(String[] args) { List
import java.util.ArrayList;gamesList = new ArrayList (); gamesList.add("Football"); gamesList.add("Cricket"); gamesList.add("Chess"); gamesList.add("Hocky"); System.out.println("Iterating by passing method reference"); gamesList.forEach(System.out::println); } } 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. Signature:
void forEachOrdered(Consumer action)
import java.util.List; public class ForEachOrderedExample { public static void main(String[] args) { List
import java.util.ArrayList;gamesList = new ArrayList (); gamesList.add("Football"); gamesList.add("Cricket"); gamesList.add("Chess"); gamesList.add("Hocky"); System.out.println("------------Iterating by passing lambda expression---------------"); gamesList.stream().forEachOrdered(games -> System.out.println(games)); System.out.println("------------Iterating by passing method reference---------------"); gamesList.stream().forEachOrdered(System.out::println); } } output: Football Cricket Chess Hocky Iterating by passing method reference Football Cricket Chess Hocky
0 Comments
Post a Comment