logo

Zanka Java forEach

Java ponuja novo metodo forEach() za ponavljanje elementov. Definiran je v vmesniku Iterable in Stream. Je privzeta metoda, definirana v vmesniku Iterable. Razredi zbirke, ki razširjajo vmesnik Iterable, lahko uporabljajo zanko forEach za ponavljanje elementov.

Ta metoda ima en sam parameter, ki je funkcionalni vmesnik. Torej lahko posredujete lambda izraz kot argument.


Podpis forEach() v ponovljivem vmesniku

 default void forEach(Consumeraction) 

Java 8 forEach() primer 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)); } } 

Izhod:

 ------------Iterating by passing lambda expression-------------- Football Cricket Chess Hocky 

2. primer Java 8 forEach().

 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); } } 

Izhod:

 ------------Iterating by passing method reference--------------- Football Cricket Chess Hocky 

Metoda Java Stream forEachOrdered().

Poleg metode forEach() ponuja Java še eno metodo forEachOrdered(). Uporablja se za ponavljanje elementov v vrstnem redu, ki ga določa tok.

Podpis:

 void forEachOrdered(Consumer action) 

Primer metode Java Stream forEachOrdered().

 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); } } 

Izhod:

 ------------Iterating by passing lambda expression--------------- Football Cricket Chess Hocky ------------Iterating by passing method reference--------------- Football Cricket Chess Hocky