Java poskytuje novú metódu forEach() na iteráciu prvkov. Je definovaný v Iterable a Stream rozhraní. Je to predvolená metóda definovaná v rozhraní Iterable. Triedy kolekcií, ktoré rozširujú rozhranie Iterable, môžu použiť cyklus forEach na iteráciu prvkov.
Táto metóda má jeden parameter, ktorým je funkčné rozhranie. Takže ako argument môžete odovzdať výraz lambda.
forEach() Signature v iterovateľnom rozhraní
default void forEach(Consumeraction)
Príklad Java 8 forEach() 1
import java.util.ArrayList; import java.util.List; public class ForEachExample { public static void main(String[] args) { List 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)); } }
Výkon:
------------Iterating by passing lambda expression-------------- Football Cricket Chess Hocky
Príklad Java 8 forEach() 2
import java.util.ArrayList; import java.util.List; public class ForEachExample { public static void main(String[] args) { List 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); } }
Výkon:
------------Iterating by passing method reference--------------- Football Cricket Chess Hocky
Java Stream pre metóduEachOrdered().
Spolu s metódou forEach() poskytuje Java ešte jednu metódu forEachOrdered(). Používa sa na iteráciu prvkov v poradí určenom prúdom.
Príroda:
void forEachOrdered(Consumer action)
Príklad metódy Java Stream forEachOrdeded().
import java.util.ArrayList; import java.util.List; public class ForEachOrderedExample { public static void main(String[] args) { List 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); } }
Výkon:
------------Iterating by passing lambda expression--------------- Football Cricket Chess Hocky ------------Iterating by passing method reference--------------- Football Cricket Chess Hocky