logo

Java forEach cilpa

Java nodrošina jaunu metodi forEach() elementu atkārtošanai. Tas ir definēts interfeisā Iterable un Stream. Tā ir noklusējuma metode, kas definēta saskarnē Iterable. Kolekciju klases, kas paplašina Iterable saskarni, var izmantot forEach cilpu, lai iterētu elementus.

Šī metode izmanto vienu parametru, kas ir funkcionāls interfeiss. Tātad, jūs varat nodot lambda izteiksmi kā argumentu.


forEach() paraksts iterējamā interfeisā

 default void forEach(Consumeraction) 

Java 8 forEach() 1. piemērs

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

Izvade:

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

Java 8 forEach() 2. piemērs

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

Izvade:

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

Java straume forEachOrdered() metodei

Kopā ar metodi forEach() Java nodrošina vēl vienu metodi forEachOrdered(). To izmanto, lai iterētu elementus straumes norādītajā secībā.

Sindaba:

 void forEachOrdered(Consumer action) 

Java Stream forEachOrdered() metodes piemērs

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

Izvade:

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