Wednesday, 14 September 2016

forEach statement in Java 8

Undoubtedly, the most important addition in Java 8 are lambda expressions and stream. Along with these features came the new forEach method to loop the collections like List and Set. Of course you can also use it with Map but with a little difference as Map doesn’t implement either the Iterable or the Collection interface.

Using forEach()

  1. Iterable interface provides forEach method as an interface default method
    default void forEach(Consumer<? super T> action)
    

    Where Consumer is the functional interface which implements the action to be performed on each iteration. If you see the default implementation of forEach in Iterable interface it is like-

    for (T t : this) {
     action.accept(t);
    }
    

    Collections like list and set implement Iterable interface so they can use forEach() directly. As example if there is a list called numList and you want to iterate it using forEach() method it can be done like -

    numList.forEach(System.out::println);
    

    Here note that method reference is used to call println method.

  2. Another way to use forEach is to get it through stream. Stream interface also has forEach method. Collection interface provides the default implementation for getting the stream instance. As example of if there is a list called numList you can convert it to stream and then call forEach method like this -

    numList.stream().forEach(System.out::println);
    

    Ofcourse you can call many other methods on the stream like filter and then at the last you can call a terminal operation like forEach to get what all elements are left after filtering.

    As example

    List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5);
    numList.stream().filter(l -> l>3).forEach(System.out::println);
    

    Output

    4
    5
    

Iterating List and Set using Iterable’s forEach

public class ForEachDemo {
    public static void main(String args[]){
        List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5);
        System.out.println("Iterating list  ");
        numList.forEach(System.out::println);
        
        Set<Integer> numSet = new HashSet<Integer>();
        numSet.add(1);
        numSet.add(2);
        System.out.println("Iterating set  ");
        numSet.forEach(System.out::println);
    }
}

Output

Iterating list  
1
2
3
4
5
Iterating set  
1
2

Using Stream and forEach

public class ForEachDemo {
    public static void main(String args[]){
        List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5);
        System.out.println("Iterating list  ");
        // numbers greater than 3
        numList.stream().filter(l -> l > 3).forEach(System.out::println);
        
        Set<Integer> numSet = new HashSet<Integer>();
        numSet.add(1);
        numSet.add(2);
        System.out.println("Iterating set  ");
        // Only even numbers
        numSet.stream().filter(s -> s%2 == 0).forEach(System.out::println);
        
    }
}

Output

Iterating list  
4
5
Iterating set  
2

Using with Map

As already mentioned Map doesn’t implement Collection interface so you have to get the Collection view of the map and then use forEach method in case you are using it after converting to stream.
Map interface also provides default implementation of forEach method so it can be used directly also.

Example code

public class ForEachDemo {
    public static void main(String args[]){
        Map<String, String> numMap = new HashMap<String, String>();
        
        numMap.put("1", "1");
        numMap.put("2", "2");
        // Directly using
        numMap.forEach((k, v) -> System.out.println("Key " + k));
        // With stream
        numMap.entrySet().stream().forEach(System.out::println);
    }
}

Output

Key 1
Key 2
1=1
2=2

That's all for this topic forEach statement in Java 8. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. interface static methods in Java 8
  2. Optional class in Java 8
  3. Overview of lambda expressions
  4. effectively final in Java 8
  5. String join() method in Java 8

You may also like -

>>>Go to Java advance topics page

No comments:

Post a Comment