Java 8 forEach is internal iterator which is used to iterate object one by one and as same like external iterator like for…loop. Here are Java 8 forEach Example.

Example 1 : List forEach Loop

List<String> languages = Arrays.asList("Java", "C", "PHP", "Net", "C");
       languages.forEach(language -> {                     // lambda example
           System.out.println(language.toUpperCase());
       });
 Output
JAVA
C
PHP
NET
C

 Example 2 : List forEach Loop using method references

public class ForEachLoop {
    public static void main(String... args) {
        List<String> languages = Arrays.asList("Java", "C", "PHP", "Net", "C++");
        languages.forEach(ForEachLoop::languageUpper);   // method reference example
    }
    public static void languageUpper(String languages){
        System.out.println(languages.toUpperCase());
    }

}
 Output
JAVA
C
PHP
NET
C++

 Example 3: Map forEach Loop

java.util.Map<String, Integer> languages = new HashMap<>();
        languages.put("Java", 1995);
        languages.put("C", 1980);
        languages.put("PHP", 2000);

        languages.forEach((key, values) -> {
            System.out.println(key + ":" + values);
        });
 Output
Java:1995
C:1980
PHP:2000

Example 4 : Stream forEach Loop

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        integers.stream()
                .filter(integer -> integer > 4)
                .forEach((integer) -> System.out.println(integer));
Output
5
6
7
8
9
10

Example 5 : ParallelStream forEach Loop

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        integers.parallelStream()                                       // parallel stream
                .filter(integer -> integer > 4)
                .forEach((integer) -> System.out.println(integer));         // forEach its will print number in un-order sequence with parallelStream
Output
7
5
9
6
10
8

Example 5 : ParallelStream forEachOrdered Loop

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        integers.parallelStream()                                           // parallel stream
                .filter(integer -> integer > 4)
                .forEachOrdered((integer) -> System.out.println(integer)); // to maintain order with  parallelStream used forEachOrdered
Output
5
6
7
8
9
10

 

 

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

Your email address will not be published. Required fields are marked *