logo

Java forEach petlja

Java nudi novu metodu forEach() za ponavljanje elemenata. Definirano je u Iterable i Stream sučelju. To je zadana metoda definirana u Iterable sučelju. Klase zbirke koje proširuju Iterable sučelje mogu koristiti forEach petlju za ponavljanje elemenata.

Ova metoda uzima jedan parametar koji je funkcionalno sučelje. Dakle, možete proslijediti lambda izraz kao argument.


forEach() Potpis u iterabilnom sučelju

 default void forEach(Consumeraction) 

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

Izlaz:

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

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

Izlaz:

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

Metoda Java Stream forEachOrdered().

Uz metodu forEach(), Java nudi još jednu metodu forEachOrdered(). Koristi se za ponavljanje elemenata u redoslijedu navedenom u toku.

Potpis:

 void forEachOrdered(Consumer action) 

Java Stream forEachOrdered() Primjer metode

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

Izlaz:

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