Home  >  Java 8

Java forEach() Example

By Arvind Rai, May 10, 2020
The Java forEach method iterates the element of the source and performs the given action. In Java 8, the Iterable interface introduces forEach as default method that accepts the action as Consumer and Map interface also introduces forEach as default method that accepts BiConsumer as action. In Java 8 the Stream has also forEach method that accepts Consumer as action. The Iterable interface is extended by Collection and hence forEach method is available for List, Set, Queue etc.
Here on this page we will provide using forEach method in detail with examples.


1. forEach() in Iterable

The java.lang.Iterable interface has introduced forEach default method in Java 8 as following.
default void forEach(Consumer<? super T> action) 
action: The action as Consumer to be performed for each element.

The above forEach method performs the given action for each element of the Iterable. The forEach will stop for either all elements have been processed or the action throws an exception. The forEach performs the actions in the order of iteration.
If action modifies the source of elements, then behavior of forEach is unspecified, unless an overriding class has specified a concurrent modification policy.

The Iterable is extended by following interfaces.
(a) java.util.Collection: We can use forEach method with List, Set, Queue etc.
(b) java.nio.file.DirectoryStream: We can use forEach method with DirectoryStream, an object to iterate over the entries in a directory. To instantiate DirectoryStream, use Files.newDirectoryStream() method.
(c) java.nio.file.Path: We can use forEach method with Path, an object that is used to locate a file in a file system. To instantiate Path, use Paths.get() method.

2. forEach() in Map

The java.util.Map interface has introduced forEach default method in Java 8 as following.
default void forEach(BiConsumer<? super K,? super V> action) 
action: The action as BiConsumer to be performed for each entry.

The above forEach method performs the given action for each entry of the Map. The forEach will stop for either all entries have been processed or the action throws an exception. The forEach performs the actions in the order of entry set iteration.
We can use forEach method for all implementation classes of Map such as HashMap, LinkedHashMap, TreeMap, ConcurrentHashMap etc.

3. forEach() in Stream

a. forEach from java.util.stream.Stream.
void forEach(Consumer<? super T> action) 
Performs the given action as Consumer for each element of this Stream.
b. forEach from java.util.stream.IntStream.
void forEach(IntConsumer action) 
Performs the given action as IntConsumer for each element of this IntStream.
c. forEach from java.util.stream.LongStream.
void forEach(LongConsumer action) 
Performs the given action as LongConsumer for each element of this LongStream.
d. forEach from java.util.stream.DoubleStream.
void forEach(DoubleConsumer action) 
Performs the given action as DoubleConsumer for each element of this DoubleStream.

4. Example with List

To use List.forEach method, we need to pass the Consumer as action. We can pass Consumer as lambda expression or method reference.
Find the code snippet with lambda expression.
List<String> techList = Arrays.asList("Java", "Spring", "Oracle");
techList.forEach(s -> System.out.println(s)); 
Find the code snippet with method reference.
techList.forEach(System.out::println); 
Find the output.
Java
Spring
Oracle

Find one more example of forEach method with List. Here we have a list of objects.
ForEachDemoWithList.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class ForEachDemoWithList {
  public static void main(String[] args) {
	List<Student> list = new ArrayList<>();
	list.add(new Student("Ram", "male"));
	list.add(new Student("Meera", "female"));
	list.add(new Student("Kabir", "male"));

	System.out.println("---Using lambda expression---");
	Consumer<Student> maleStds = (Student s) -> {
	  if ("male".equals(s.getGender())) {
		System.out.print(s.getName() + " ");
	  }
	};

	list.forEach(maleStds);

	System.out.println("\n---Using method reference---");
	list.forEach(Student::printMaleStds);
  }
}
class Student {
  private String name;
  private String gender;
  public Student(String name, String gender) {
	this.name = name;
	this.gender = gender;
  }
  public void printMaleStds() {
	if ("male".equals(getGender())) {
	  System.out.print(getName() +" ");
	}
  }
  //Sets and Gets
} 
Output
---Using lambda expression---
Ram Kabir 
---Using method reference---
Ram Kabir  

5. Example with Set

To use Set.forEach method, we need to pass Consumer as lambda expression or method reference.
Create a Set.
Set<Integer> set = new HashSet<>();
set.add(15); 
set.add(10);
set.add(20); 
Use forEach with lambda expression to print the data.
set.forEach(s -> System.out.println(s)); 
Use method reference.
set.forEach(System.out::println); 

Find one more example to use forEach with Set.
ForEachDemoWithSet.java
package com.concretepage;
import java.util.HashSet;
import java.util.Set;
public class ForEachDemoWithSet {
  public static void main(String[] args) {
	Set<Book> books = new HashSet<>();
	books.add(new Book("Book A", 60));
	books.add(new Book("Book B", 30));
	books.add(new Book("Book C", 40));

	// With lambda expression
	books.forEach(b -> {
	  if (b.getPrice() < 50) {
		System.out.println(b.getName());
	  }
	}); //Output: Book B, Book C
	
	// With method reference
	books.forEach(Book::printBook); //Output: Book B, Book C
  }
}
class Book {
  private String name;
  private int price;
  public Book(String name, int price) {
	this.name = name;
	this.price = price;
  }
  public void printBook() {
	if (price < 50) {
	  System.out.println(name);
	}
  }
  //Sets, Gets, equals, hashCode
}
 

6. Example with Queue

To use Queue.forEach method, we need to pass Consumer as lambda expression or method reference.
Find the example of forEach with Queue. We are instantiating Queue with its implementation class ArrayDeque here.
ForEachDemoWithQueue.java
package com.concretepage;
import java.util.ArrayDeque;
public class ForEachDemoWithQueue {
  public static void main(String[] args) {
	ArrayDeque<String> queue = new ArrayDeque<String>();
	queue.add("BB");
	queue.add("CC");

	queue.offerFirst("AA");
	queue.offerLast("DD");

	// With lambda expression
	queue.forEach(e -> System.out.println(e)); //AA, BB, CC, DD

	// With method reference
	queue.forEach(System.out::println); //AA, BB, CC, DD
  }
} 

7. Example with DirectoryStream

To use DirectoryStream.forEach method, we need to pass Consumer as lambda expression or method reference.
Find the example of forEach with DirectoryStream using lambda expression.
WithDirectoryStream.java
package com.concretepage;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class WithDirectoryStream {
  public static void main(String[] args) throws IOException {
	  Path dir = Paths.get("C:/page");
	  DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir, "*.{txt,jpg}");

	  dirStream.forEach(f -> System.out.println(f.getFileName()));
  }
} 

8. Example with Path

To use Path.forEach method, we need to pass Consumer as lambda expression or method reference.
Find the example of forEach with Path using lambda expression.
ForEachDemoWithPath.java
package com.concretepage;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ForEachDemoWithPath {
  public static void main(String[] args) {
	  Path dir = Paths.get("C:/page/java/java8/myclass.java");
	  dir.forEach(f -> System.out.println(f.getFileName()));
  }
} 

9. Example with Map

To use Map.forEach method, we need to pass BiConsumer as lambda expression or method reference.
Suppose we have following Map.
Map<Integer, String> map = new HashMap<>();
map.put(101, "Java");
map.put(102, "Angular");
map.put(103, "Spring"); 
Find the forEach to iterate the Map.
map.forEach((k, v) -> System.out.println(k + "-" + v)); 
We will get following output.
101-Java
102-Angular
103-Spring 

Find one more example of forEach with Map.
ForEachDemoWithMap.java
package com.concretepage;
import java.util.HashMap;
import java.util.Map;
public class ForEachDemoWithMap {
  public static void main(String[] args) {
	Map<Integer, User> map = new HashMap<>();
	map.put(101, new User("Mahesh", true));
	map.put(102, new User("Suresh", false));
	map.put(103, new User("Krishn", true));

	System.out.println("---Passing BiConsumer as lambda expression---");
	map.forEach((k, v) -> {
	  if (v.isActive() == true) {
		System.out.println(k + " - " + v.getUserName());
	  }
	});

	System.out.println("---Passing BiConsumer as method reference---");
	map.forEach(User::printActiveUser);
  }
}
class User {
  private String userName;
  private boolean active;

  public User(String userName, boolean active) {
	this.userName = userName;
	this.active = active;
  }
  public static void printActiveUser(int id, User user) {
	if (user.isActive() == true) {
	  System.out.println(id + " - " + user.getUserName());
	}
  }
  //Sets and Gets
} 
Output
---Passing BiConsumer as lambda expression---
101 - Mahesh
103 - Krishn
---Passing BiConsumer as method reference---
101 - Mahesh
103 - Krishn 

10. Example with Stream

To use Stream.forEach method, we need to pass Consumer as lambda expression or method reference. Find the example.
ForEachDemoWithStream1.java
package com.concretepage;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class ForEachDemoWithStream1 {
  public static void main(String[] args) {
	Stream<String> stream = Stream.of("Mahesh", "Nilesh", "Mohit");
	stream.forEach(e -> System.out.println(e)); //Mahesh, Nilesh, Mohit

	List<String> list = Arrays.asList("Mahesh", "Nilesh", "Mohit");
	list.stream().filter(e -> e.startsWith("M")).forEach(e -> System.out.println(e)); //Mahesh, Mohit
	
	list.stream().filter(e -> e.startsWith("M")).forEach(System.out::println); //Mahesh, Mohit
	
	list.stream().sorted().forEach(e -> System.out.println(e)); //Mahesh, Mohit, Nilesh
  }
} 

To use forEach method with IntStream pass IntConsumer, with LongStream pass LongConsumer and with DoubleStream pass DoubleConsumer as action.
Find the example.
ForEachDemoWithStream2.java
package com.concretepage;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class ForEachDemoWithStream2 {
  public static void main(String[] args) {
    // With IntStream
    IntStream.of(30, 40, 50).forEach(s -> System.out.println(s)); //30, 40, 50
    IntStream.of(30, 40, 50).forEach(System.out::println); //30, 40, 50
	
    IntStream.of(30, 40, 50).flatMap(e -> IntStream.of(e / 10))
	    .forEach(e -> System.out.println(e)); //3, 4, 5

    // With LongStream	
    LongStream.of(300, 400, 500).forEach(s -> System.out.println(s)); //300, 400, 500
    LongStream.of(300, 400, 500).forEach(System.out::println); //300, 400, 500
	
    LongStream.of(300, 400, 500).flatMap(e -> LongStream.of(e / 100))
	    .forEach(e -> System.out.println(e)); //3, 4, 5
	
    // With DoubleStream
    DoubleStream.of(30.15, 40.35, 50.55).forEach(s -> System.out.println(s)); //30.15, 40.35, 50.55
    DoubleStream.of(30.15, 40.35, 50.55).forEach(System.out::println); //30.15, 40.35, 50.55
	
    DoubleStream.of(30.15, 40.35, 50.55).flatMap(e -> DoubleStream.of(e * 10))
	    .forEach(e -> System.out.println(e)); //301.5, 403.5, 505.5    
  }
} 

11. References

Java doc: Iterable
Java doc: Map
Java doc: Stream
POSTED BY
ARVIND RAI
ARVIND RAI








©2020 concretepage.com | Privacy Policy | Contact Us