HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java 8 / Java 8 forEach()

Java 8 forEach()

The Java forEach() method is a utility function to iterate over a collection such as (list, set or map) and stream. It is used to perform a given action on each the element of the collection.

The forEach() method has been added in following places:

  • Iterable interface – This makes Iterable.forEach() method available to all collection classes except Map
  • Map interface – This makes forEach() operation available to all map classes.
  • Stream interface – This makes forEach() and forEachOrdered() operations available to all types of stream.

1. Iterable forEach()

1.1. forEach() Method

The given code snippet shows the default implementation of forEach() method in Iterable interface.

Internally it uses the enhanced for-loop. So using the new for-loop will give the same effect and performance as forEach() method.

default void forEach(Consumer<? super T> action) 
{
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

The forEach() method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Example 1: Java program to iterate over a List using forEach()

List<String> names = Arrays.asList("Alex", "Brian", "Charles");
	
names.forEach(System.out::println);

Program Output:

Alex
Brian
Charles

1.2. Creating consumer action

In above example, the action represents an operation that accepts a single input argument and returns no result. It is an instance of Consumer interface.

By creating the consumer action like this, we can specify multiple statements to be executed in a syntax similar to a method.

List<String> names = Arrays.asList("Alex", "Brian", "Charles");

Consumer<String> makeUpperCase = new Consumer<String>()
{
    @Override
    public void accept(String t) 
    {
    	System.out.println(t.toUpperCase());
    }
};

names.forEach(makeUpperCase);	

Program Output:

ALEX
BRIAN
CHARLES

2. Map forEach()

2.1. forEach() Method

This method performs the given BiConsumer action for each Entry in this Map until all entries have been processed or the action throws an exception.

default void forEach(BiConsumer<? super K, ? super V> action) {
    Objects.requireNonNull(action);
    for (Map.Entry<K, V> entry : entrySet()) {
        K k;
        V v;
        try {
            k = entry.getKey();
            v = entry.getValue();
        } catch(IllegalStateException ise) {
            // this usually means the entry is no longer in the map.
            throw new ConcurrentModificationException(ise);
        }
        action.accept(k, v);
    }
}

Example 2: Java program to iterate over a Map using forEach()

Map<String, String> map = new HashMap<String, String>();

map.put("A", "Alex");
map.put("B", "Brian");
map.put("C", "Charles");

map.forEach((k, v) -> 
	System.out.println("Key = " + k + ", Value = " + v));

Program Output:

Key = A, Value = Alex
Key = B, Value = Brian
Key = C, Value = Charles

We can also create a custom BiConsumer action which will take key-value pairs from Map and process each entry one at a time.

BiConsumer<String, Integer> action = (a, b) -> 
{ 
	//Process the entry here as per business
    System.out.println("Key is : " + a); 
    System.out.println("Value is : " + b); 
}; 

Map<String, Integer> map = new HashMap<>();
    
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

map.forEach(action);

Program output.

Key is : A
Value is : 1

Key is : B
Value is : 2

Key is : C
Value is : 3

3. Stream forEach() and forEachOrdered()

In Stream, forEach() and forEachOrdered() are terminal operations.

Similar to Iterable, stream forEach() method performs an action for each element of the stream.

For sequential streams, the order of elements (during iteration) is same as the order in the stream source, so the output would be same whether we use forEach() or forEachOrdered().

while using parallel streams, use forEachOrdered() if order of the elements matter during the iteration. forEach() method does not gaurantee the element ordering to provide the advantages of parallelism.

Example 3: Java forEach() example to iterate over Stream

In this example, we are printing all the even numbers from a stream of numbers.

List<Integer> numberList = Arrays.asList(1,2,3,4,5);
    
Consumer<Integer> action = System.out::println;

numberList.stream()
	.filter(n -> n%2  == 0)
	.forEach( action );

Program output.

2
4

Example 4: Java forEachOrdered() example to iterate over Stream

In this example, we are printing all the even numbers from a stream of numbers.

List<Integer> numberList = Arrays.asList(1,2,3,4,5);
    
Consumer<Integer> action = System.out::println;

numberList.stream()
	.filter(n -> n%2  == 0)
	.parallel()
	.forEachOrdered( action );

Program output.

2
4

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Gaurav Pathak

    February 24, 2020

    as i can see on this page :
    “1. Java 8 forEach method
    Below code snippet shows the default implementation of java forEach method in Iterable interface. It makes this method available to all collection classes except Map.”

    it is written here that forEach() method is not available in Map interface is Wrong , please check and update the information , because as i can see in my “public interface Map” there is a “default void forEach(BiConsumer action)” method is available @since java 8.

    correct me if i am wrong.

    • Lokesh Gupta

      February 25, 2020

      Thanks Gaurav for sharing. I had missed to cover this method. The post is updated now.

      • Gaurav Pathak

        April 18, 2020

        Hello Lokesh , the post is not updated yet. please go to the section “1.1. Iterable.forEach()” and check it is still showing that forEach() method available to all collection classes “except” Map. whereas this method is available for Map also.

        If I’m incorrect/mistaken, I apologize.

        • Lokesh Gupta

          April 18, 2020

          Hi Gaurav, Please refer to section 1.2 which talks about forEach() in Map. Section 1.1 talks about Iterable.forEach() which is not implemented by Map. Both are different.

  2. Javeed Ahmed Sayed

    August 19, 2019

    Thank you for doing this. I have been searching a lot for this 🙂

Comments are closed on this article!

Search Tutorials

Java 8 Tutorial

  • Java 8 Features
  • Java 8 forEach
  • Java 8 Stream
  • Java 8 Boxed Stream
  • Java 8 Lambda Expression
  • Java 8 Functional Interface
  • Java 8 Method Reference
  • Java 8 Default Method
  • Java 8 Optional
  • Java 8 Predicate
  • Java 8 Regex as Predicate
  • Java 8 Date Time
  • Java 8 Iterate Directory
  • Java 8 Read File
  • Java 8 Write to File
  • Java 8 WatchService
  • Java 8 String to Date
  • Java 8 Difference Between Dates
  • Java 8 Join Array
  • Java 8 Join String
  • Java 8 Exact Arithmetic
  • Java 8 Comparator
  • Java 8 Base64
  • Java 8 SecureRandom
  • Internal vs External Iteration

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces