Guide To Java 8 forEach Method With Example

May 02, 2022
Xblog GuidetoJava8forEachmethodwith example



Introduction

ForEach java was first Introduced in Java 8. It is a method used to create loops just like for-loop and while-loop. The forEach method in Java provides Java developers with a new and simple way to iterate maps, lists, sets, or streams.

In this article, we will see how to use forEach in Java, the number of arguments it takes and their types, and how the forEach Java method is different from other loops like for-loop or enhanced for-loop.

new java job roles

forEach Java method

The forEach Java method is part of the stream interface and is used to execute a particular operation, defined by a consumer.

Following is the syntax of the forEach Java method:

void forEach(Consumer<? super T> action)

The Javadoc states for forEach that it “performs the given action for each element of the iterable until all elements have been processed or the action throws an exception.”

It means you can iterate over a collection and perform any action on every element, like done using any other Iterator tool. The action is contained in a class that implements the consumer interface and is then passed to forEach method as an argument.

See this example where for-loop is used to iterate and print a collection of Strings:

1. for (String ID : Ids) {
2.    System.out.println(ID);
3. }

Now, this same thing can be done using forEach method like this:

1. names.forEach(ID -> {
2.     System.out.println(ID);
3. });

What is consumer interface?

The consumer interface is functional means it has a single abstract method. It represents an operation that takes an argument as input but returns no output.

Following is the definition of the consumer interface:

1. @FunctionalInterface
2. public interface Consumer {
3.     void accept(T t);
4. }

Any action for instance, printing a string can be passed to forEach method as an argument:

1. Consumer<String> printConsumer = new Consumer<String>() {
2.     public void accept(String name) {
3.        System.out.println(name);
4.     };
5. };
6.  names.forEach(printConsumer);

It is one of many ways to create an action using a consumer and use forEach method.

How to use the forEach Java method

Following are the three most used ways to use the forEach Java method:

· Anonymous consumer implementation

The consumer interface can be implemented using an anonymous class and then it can be applied as an argument to the forEach method.

See this example below:

1. Consumer<String> newConsumer = new Consumer<String>() {
2.    public void accept(String days) {
3.        System.out.println(days);
4.     }
5.  };
6. days.forEach(newConsumer);

This works fine but if you notice the example, you can observe that the main logic is the code inside the accept() method which makes the code unnecessarily lengthy.

· Lambda expression

One of the benefits of Java 8 functional interfaces is that it allows the use of lambda expressions to instantiate the consumer interface. It is simple and gives an alternative to developers to avoid using bulky anonymous class implementations.

The above-mentioned code using anonymous class Implementation can be simplified like this:

days -> System.out.println(days)

Now it can be passed to forEach:

days.forEach(days -> System.out.println(days));

· Method reference

The method reference syntax can also be used instead of the Lambda syntax, in this case, a method already exists to operate on the class like this:

days.forEach(System.out::println);

Applications of forEach Java method

· Iterating over a collection

Any collection type that can be iterable like a queue, list, and set, all follows a very similar syntax for implementing the forEach method. It is to be noted that the forEach method can be used on any collection.

Following is an example of iterating elements of a list in Java:

1. List<String> days = Arrays.asList("Monday", "Tuesday", "Wednesday", "Thursday", 
   "Friday", "Saturday", "Sunday");
2. days.forEach(System.out::println);

In a very similar way, forEach Java method can be used for sets:

1. Set<String> days = new HashSet<>(Arrays.asList("Monday", "Tuesday", "Wednesday", 
   "Thursday", "Friday", "Saturday", "Sunday");
2. days.forEach(System.out::println);

Lastly, this is an example for iterating queue that is also a collection:

1. Queue<String> days = new ArrayDeque<>(Arrays.asList("Monday", "Tuesday", 
   "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
2. days.forEach(System.out::println);

All three of these examples will have the same following output:

Output:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

· Iterating over a map

A Map is not an Iterable type, but there are two ways to iterate a map using forEach:

1. Using map’s forEach method

Java 8 has introduced a BiConsumer that can be used in place of the consumer interface for iterating maps using the forEach method. Using BiConsumer, an action can be performed on both the key and value of a map simultaneously.

See this detailed example of iterating a map using forEach Java method:

1.  import java.util.Map;
2.  import java.util.HashMap;
3.  public class forEachExample {
4.  public static void main(String[] args) {
5.       Map<Integer, String> days = new HashMap<Integer, String>();
6.       days.put(1, "Monday");
7.       days.put(2, "Tuesday");
8.       days.put(3, "Wednesday");  
9.       days.put(4, "Thursday");  
10.      days.put(5, "Friday");  
11.      days.put(6, "Saturday");
12.      days.put(7, "Sunday");
13.//forEach used to iterate and display each key along with thair value pair of Hashmap  
14.      days.forEach((key,value)->System.out.println(key+" - "+value));
15.//Using forEach to iterate a Map and display the value of the entered key    
16.       days.forEach((key,value)->{
17.         if(key == 4){
18.            System.out.println("4th day of the week is "+value);
19.         }  
20.      });    
21.//using forEach to iterate a Map and display the key associated with a given value
22.         hmap.forEach((key,value)->{
23.         if("Friday".equals(value)){
24.            System.out.println("Friday is the"+key+"day of the week");
25.          }
26.       }); 
27.    }
28.  }

Output:

1 – Monday
2 – Tuesday
3 – Wednesday
4 – Thursday
5 – Friday
6 – Saturday
7 – Sunday
4th day of the week is Thursday
Friday is the 5 day of the week

As you can see here, BiConsumer is used to iterate over the entries of the Map like this:

(key, value) -> System.out.println(key + " - " + value)

2. By Iterating entry set

Another way to iterate a Map is iterating the EntrySet of the map using forEach. As the entries of a map are stored in a Set called “EntrySet”, that set can be iterated like this,

1. namesMap.entrySet().forEach(entry -> System.out.println(
2.   entry.getKey() + " - " + entry.getValue()));

· Iterating over a stream

Along with the forEach java method, the stream was also Introduced in Java 8. The stream is used to process collections of objects.  It is not a data structure instead it takes input from the collections, arrays, or I/O channels and applies operations like Sorted(), filter(), and more on the data. ForEach method is one of them.

In the following example a stream is iterated using forEach() method:

1. import java.util.List;
2. import java.util.ArrayList;
3. public class streamExample {
4.    public static void main(String[] args) {
5.       List<String> days = new ArrayList<String>();
6.       days.add("Monday");
7.       days.add("Tuesday");
8.       days.add("Wednesday");
9.       days.add("Thursday");
10.      days.add("Friday");
11.      days.add("Saturday");
12.      days.add("Sunday");
13.      days.stream() //the stream is created
14       .filter(f->f.startsWith("T")) //filtering out the days that starts with T
15       .forEach(System.out::println); //Now, iterating the stream using forEach to 
16       //display the filtered days
17.   }
18. }

Output:

Tuesday
Thursday

ForEach Java method vs For-Loop

Java forEach method is far more efficient than a simple for-loop as a simple for-loop is incapable of iterating a collection, a list, or a map.

When it comes to enhanced for loop, both loops provide the same functionality, they both iterate through elements in a collection. However, the main difference between them is that they are different types of iterators. The enhanced for-loop is an external iterator, whereas the new forEach method is an internal one.

· Internal Iterator:

An internal Iterator manages the iterations in the background and allows the programmer to make whatever changes are required to the elements of the collection. It requires less code as well as it is relatively easier to implement.

· External iterators:

In external iterators like for-loop, the programmer has to define when and how the next element of iteration will be called. It is a bit more flexible but complex than an internal iterator which makes it prone to errors. Enumerations, Iterators, and enhanced for-loop are all external iterators.

Unlike an internal iterator where the iterator does the iteration itself, here it requires a line of code by the programmer that takes every element out of the collection.

See Also: Formatting With printf() In Java

Conclusion

We discussed the basics of using a forEach Java method and how to implement it on a list, map, and set with examples as well as how it differs from other iterative methods.

The forEach method is very useful to iterate over collections in Java in a functional approach. In many cases, using forEach can significantly simplify the code, making it more readable.

new Java jobs



author

shaharyar-lalani

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US