Pages

Sunday, August 16, 2020

Java 8 forEach Examples on List, Set and Map

1. Overview

In this tutorial, We'll learn how to use forEach method which is introduced in Java 8.

We will work on forEach examples before and after java 8 on List and Map.

Java 8 made a revolution to support Functional programmings such as using Streams and Functional Interfaces.

A Stream can be created for any collection such as from List, Set and Map. Stream API also has a method named forEach() to iterate collection in sequential and parallel mode. This stream for each very effective. We will be showing the examples on each.

Java 8 forEach Examples


All Collection classes implement the Iterable interface which has forEach() method. This forEach() method is a default method in it and can be invoked on every collection class such as ArrayList, Hashset, Treeset.

But, the Separate forEach(BiConsumer biConsumer) method is implemented in the Map interface as the default method. This is invoked on any Map implementation such as HashMap, TreeHashMap, and LinkedHashMap.


2. Java 8 forEach List Example


Example programs before and after java 8 on iterating ArrayList using forEach.

// Creating List

List fruits = new ArrayList<>();
fruits.add("Orange");
fruits.add("Jack Fruit");
fruits.add("Mango");
fruits.add("Apple");

2.1  Normal way to use foreach on List

List - Normal for each loop

for (String fruit : fruits) {
 System.out.println("Fruit name: " + fruit);
}

Output:

Fruit name: Orange
Fruit name: Jack Fruit
Fruit name: Mango
Fruit name: Apple

List - Normal for loop - to print even number index fruits.


for (int i = 0; i < fruits.size(); i++) {

 if (i % 2 == 0) {
  System.out.println(fruits.get(i));
 }
}

Output:

Orange
Mango

2.2 Java 8 List forEach Example

fruits.forEach(fruit -> System.out.println("Foreach fruIT : " + fruit));

Output:

Foreach fruIT : Orange
Foreach fruIT : Jack Fruit
Foreach fruIT : Mango
Foreach fruIT : Apple

3. Java 8 forEach Set Example


Set example programs using iterate and foeEach in java 8. We will show examples in each case. These are very useful when working with stream operations.

// Creating Hashset
Set countriesSet = new HashSet();
countriesSet.add("USA");
countriesSet.add("Canada Fruit");
countriesSet.add("Australia");
countriesSet.add("India");

3.1 Normal way to iterate Set using Iterator

// Set - Iterator

Iterator iterator = countriesSet.iterator();

while (iterator.hasNext()) {
 System.out.println("Set iterator : " + iterator.next());
}

Output:

Set iterator : USA
Set iterator : Australia
Set iterator : Canada Fruit
Set iterator : India

3.2 Java 8 Set forEach Example

A new forEach() method is introduced in Java 8 Set interface.

countriesSet.forEach(str -> System.out.println("Java 8 Set forEach "+str));

Output:

Java 8 Set forEach USA
Java 8 Set forEach Australia
Java 8 Set forEach Canada Fruit
Java 8 Set forEach India

4. Java 8 forEach Map Example

Writing Map iteration using a normal way and Java 8 forEach() method.

4.1 looping Map in a normal way

The Map can be iterated in multiple ways. All are discussed in the previous article on Iterating Map in Java.

for (Map.Entry entry : countryStatesCountMap.entrySet()) {
 System.out.println("Country name : " + entry.getKey() + " States Count : " + entry.getValue());
}

Output:

Country name : USA States Count : 45
Country name : Pakistan States Count : 10
Country name : India States Count : 25

4.2 Java 8 Map forEach Example


The Map interface is provided with a forEach() default method which takes BiConsumer as an argument.

BiConsumer is a Function Interface in java 8 and its functional method is accept(T t, U u). This method takes two arguments and does return nothing.

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


In iterating map using forEach(k, v) - Takes key and value as arguments for Lambda forEach here.

Output:

Key USA , Value : 45
Key Pakistan , Value : 10
Key India , Value : 25

5. Java 8 Stream.forEach() Example


As of now, We've seen using iterating or looping a collection using inbuilt forEach function in Iterable and Map interface.

Now, We'll see examples now using the Stream API forEach method. But, this works for List and Set only. It does not work for Map.

void forEach(Consumer action)

This is a terminal operation that means this is used to produce a result (ending of Stream).

Note: If the parallel stream is chosen then the order of executing forEach() method will be different than elements present in the original collection. To preserve the order for parallel streams, we should use forEachOrdered(Consumer action).

See the below example java programs using Stream API.

// List Stream forEach Example
fruits.stream().forEach(value -> System.out.println(value));

// Set Stream forEach Example
countriesSet.stream().forEach(country -> System.out.println(country));

This example snippet will produce the same output as seen in the previous sections.

6. Conclusion


In this tutorial, We've seen practical Java 8 programs to iterate using forEach() method for List, Set and Map.

Iterable has a default forEach(Consumer consumer) method which takes Consumer as an argument. This is for List and Set implementations.

Map interface has forEach(BiConsumer<K, V> action) and this is also a default mehtod. This works for all Map implementations.

Apart from these mehtods, New Java 8 Stream API also introduced a forEach(Consumer action). This method does not gareentee that order will be the same as in collection when working with parallel streams. To maintain an execution order, we should use forEachOrdered() method.

The complete code is available over GitHub.

No comments:

Post a Comment

Please do not add any spam links in the comments section.