Java 8 forEach


The Java forEach is a utility method to iterate over a collection or stream and perform a certain action on each element of it.

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.

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

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

A custom action can be created using this simple syntax. Here Object type shall be replaced with the type of elements in the collection or stream.

Consumer<Object> action = new Consumer<Object>()
{
    @Override
    public void accept(Object t) 
    {
        //perform action
    }
};

Java 8 stream forEach example

Java program to iterate over all elements of a stream and perform an action. In this example, we are printing all even numbers.

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

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

Java forEach example using List

Java program to iterate over all elements of an arraylist and perform an action. Here action is as simple as printing out the element in console.

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

numberList.forEach(action);
Program output.
1
2
3
4
5

Java forEach example using Map

Java program to iterate over all entries of and perform an action. We can also iterate over map keys and values and perform any action on all elements.

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

//1. Map entries
Consumer<Map.Entry<String, Integer>> action = System.out::println;

map.entrySet().forEach(action);

//2. Map keys
Consumer<String> actionOnKeys = System.out::println;

map.keySet().forEach(actionOnKeys);

//3. Map values
Consumer<Integer> actionOnValues = System.out::println;

map.values().forEach(actionOnValues);
output
A=1
B=2
C=3

A
B
C

1
2
3





javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition