HomeCore JavaJava 8 forEach - Examples

Java 8 forEach – Examples


forEach method introduced in Java 8, which is used to iterate or loop each element of Collection or Map or Stream. In this article we will see examples for processing List, Map, Stream using forEach method.

 Java forEach method present in 3 interfaces, they are, Iterable Stream and other one is Map.

forEach Method Signature :

default void forEach(Consumer<? super T> action)

Collection classes which extends Iterable interface can use forEach method to iterate elements. This method takes a single parameter which is Consumer functional interface. As this is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

Order in forEach method : The behavior of this operation is explicitly non deterministic. Order is depends on the which implementation or source that we are perform on forEach method. For parallel stream pipelines this operation does not guarantee Order.

1. Java forEach List example

Following example shows you how to iterate List using Java 8 forEach method.

public class ForEachListDemo {
    
    public static void main(String[] args) {
        
        List<String> list = new ArrayList<>();
        list.add("Peter");
        list.add("Gerhard");
        list.add("Philip");
        list.add("John");
        
        // forEach using lambda
        list.forEach(value -> System.out.println(value));
        
        // forEach using method reference
        list.forEach(System.out::println);  
    }
} 

2. Java 8 forEach Stream example

Following example shows you how to iterate Java Stream using forEach method.

public static void main(String[] args) {
        
        List<String> list = new ArrayList<>();
        list.add("Peter");
        list.add("Gerhard");
        list.add("Philip");
        list.add("John");
        
        System.out.println("---- forEach using stream ----");
        list.stream().forEach(value -> System.out.println(value));
        
        System.out.println("---- filter and forEach ----");
        list.stream() // Creating Stream from collection source
            .filter(name -> name.startsWith("P")) // Intermediate Operation
            .forEach(System.out::println); // Terminal Operation 
    }
}

Output :

---- forEach using stream ----
Peter
Gerhard
Philip
John
---- filter and forEach ----
Peter
Philip

3. Java forEach Map example

Following example shows you how to use forEach method to the maps, you can convert a Map.entrySet() or Map.keySet() into a stream, follow by a filter() and collect() it.

public static void main(String[] args) {
        
        Map<Integer, String> namesMap = new LinkedHashMap<Integer, String>();
        namesMap.put(1, "Peter");
        namesMap.put(2, "Martin");
        namesMap.put(3, "John");
        namesMap.put(4, "Mike");
        namesMap.put(5, "Vijay");
        namesMap.put(6, "Miller");
        
        System.out.println("---- forEach using map ----");
        namesMap.forEach((k,v) -> {
			System.out.println("Id: "+ k+ ", Name: "+ v);
		});
       
        System.out.println("---- Stream filter and forEach ----");
        namesMap.entrySet()
            .stream()
            .filter(kv -> kv.getValue().contains("M") ) 
            .forEach(System.out::println); 
    }
}

Output :

---- forEach using map ----
Id: 1, Name: Peter
Id: 2, Name: Marting
Id: 3, Name: John
Id: 4, Name: Mike
Id: 5, Name: Vijay
Id: 6, Name: Miller
---- Stream filter and forEach ----
2=Martin
4=Mike
6=Miller

4. forEach with Consumer

Following example shows you how to create a basic Java Consumer Function and provide Consumer function to the forEach().

public class ForEachConsumerDemo {
    
    public static void main(String[] args) {
        
        List<String> list = new ArrayList<>();
        list.add("Peter");
        list.add("Gerhard");
        list.add("Philip");
        list.add("John");
        
        //Consumer Example
        Consumer<String> c = name -> {
            if(name.startsWith("P"))
               System.out.println(name);;
        };
        list.forEach(c);
    }
}

Output :

Peter
Philip

5. forEach parallel Stream example

Following example shows you how forEach() and forEachOrdered() works with parallel streams.

public class ForEachParallelStreamDemo {
	
    public static void main(String[] args) {
    	
        Map<Integer, String> userMap = new LinkedHashMap<Integer, String>();
        userMap.put(6, "Peter");
        userMap.put(2, "Gerhard");
        userMap.put(4, "Catherine");
        userMap.put(1, "Philip");
        
        System.out.println(userMap);
        System.out.println("----- no prallel, order as provided stream -----");  
        userMap.keySet()
            .stream()
            .forEach(key -> System.out.println("ID: "+key+" User: "+ userMap.get(key)));  
        
        System.out.println("----- prallel, order no guarantee -----");  
        userMap.keySet()
            .parallelStream()
            .forEach(key -> System.out.println("ID: "+key+" User: "+ userMap.get(key))); 
        
        System.out.println("----- prallel, order guarantee if uses forEachOrdered -----");  
        userMap.keySet()
            .parallelStream()
            .forEachOrdered(key -> System.out.println("ID: "+key+" User: "+ userMap.get(key))); 
    }
}

Output :

{6=Peter, 2=Gerhard, 4=Catherine, 1=Philip}
----- no prallel, order as provided stream -----
ID: 6 User: Peter
ID: 2 User: Gerhard
ID: 4 User: Catherine
ID: 1 User: Philip
----- prallel, order no guarantee -----
ID: 4 User: Catherine
ID: 1 User: Philip
ID: 2 User: Gerhard
ID: 6 User: Peter
----- prallel, order guarantee if uses forEachOrdered -----
ID: 6 User: Peter
ID: 2 User: Gerhard
ID: 4 User: Catherine
ID: 1 User: Philip

6. Conclusion

In this article we have covered several examples using Java 8 forEach method, using List, Map and Stream. And also we have shown examples on how forEach() and forEachOrdered() method behavior on order of the elements with respective to parallel and non parallel Streams.

7. References :

  1. Stream documentation
  2. Java BiFunction Examples
  3. Java Predicate examples
  4. Java 8 Stream map examples

LEAVE A REPLY

Please enter your comment!
Please enter your name here