$show=/label

Java 8 forEach Examples on List, Set and Map

SHARE:

A quick practice guide to working java 8 forEach examples for List, Set and Map. And also an example to Stream.forEach(Consumer consumer).

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.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 forEach Examples on List, Set and Map
Java 8 forEach Examples on List, Set and Map
A quick practice guide to working java 8 forEach examples for List, Set and Map. And also an example to Stream.forEach(Consumer consumer).
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_R_ANoauPiUbfiokRusyyycUugMCg_3d6yTI515-AMwKWwyB5PFqZ-N-usz9GpbgNkABCfH2OxSee-CWtM-zc9pqYGWSnYfXysW7iOlaYRQk488NfnRVcwS5D9UnyXNv69P6AwNzl1Og/s320/Java+8+forEach+Examples.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_R_ANoauPiUbfiokRusyyycUugMCg_3d6yTI515-AMwKWwyB5PFqZ-N-usz9GpbgNkABCfH2OxSee-CWtM-zc9pqYGWSnYfXysW7iOlaYRQk488NfnRVcwS5D9UnyXNv69P6AwNzl1Og/s72-c/Java+8+forEach+Examples.png
JavaProgramTo.com
https://www.javaprogramto.com/2019/07/java-8-foreach.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/07/java-8-foreach.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content