Home core java java 8 forEach method with list map stream examples

java 8 forEach method with list map stream examples


Java 8 forEach method is to process each element of Collection or Map or Stream, introduced in Java 8. Java foraEch method present in 3 interfaces one is Iterable Stream and other one is Map. In this article we will see examples for processing list, map, stream using forEach method.

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 method example on List

Following example shows you how to iterate List using 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 method example using Stream :

Following example shows you how to iterate 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 method example using Map

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. Example using Consumer :

Following example shows you how to create a basic 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 example using parallel Stream

Following example shows you how forEach() and orEachOrdered() 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

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.

References :

  1. Stream documentation

Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Also founder of javabydeveloper.com. Follow him on LinkedIn or Twitter or Facebook

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories

Related Articles