logo

Java for hver sløjfe

Java giver en ny metode forEach() til at iterere elementerne. Det er defineret i Iterable og Stream-grænsefladen. Det er en standardmetode, der er defineret i Iterable-grænsefladen. Samlingsklasser, der udvider Iterable-grænsefladen, kan bruge forHver sløjfe til at iterere elementer.

Denne metode tager en enkelt parameter, som er en funktionel grænseflade. Så du kan sende lambda-udtryk som et argument.


forEach()-signatur i Iterable Interface

 default void forEach(Consumeraction) 

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

Produktion:

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

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

Produktion:

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

Java Stream forEachOrdered() metode

Sammen med forEach()-metoden giver Java endnu en metode forEachOrdered(). Det bruges til at iterere elementer i den rækkefølge, der er angivet af strømmen.

Singnature:

 void forEachOrdered(Consumer action) 

Java Stream forEachOrdered()-metodeeksempel

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

Produktion:

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