10 Examples of forEach() method in Java 8

From Java 8 onward, you can iterate over a List or any Collection without using any loop in Java. The new Stream class provides a forEach() method, which can be used to loop over all or selected elements of list and map. forEach() method provides several advantage over traditional for loop e.g. you can execute it in parallel by just using a parallel Stream instead of regular stream. Since you are operating on stream, it also allows you to filter and map elements. Once you are done with filtering and mapping, you can use forEach() to operate over them. You can even use method reference and lambda expression inside forEach() method, resulting in more clear and concise code. If you not started with Java 8 yet than you should make it one of your new year resolution for 2016. Coming years will see much more adoption of Java 8. If you are looking for a good book to learn Java 8, than you can use Java 8 in Action, one of the best book about lambda expression, stream and other functional aspect of Java 8. For now, let's see a couple of examples of forEach() in Java 8.


How to use forEach() method in Java 8

Now you know a little bit about the forEach() method and Java 8, it's time to see some code examples and explore more of forEach() method in JDK 8.


Iterating over all elements of List using forEach()
You can loop over all elements using Iterable.forEach() method as shown below:

List<String> alphabets = new ArrayList<>(Arrays.asList("aa", "bbb", "cat", "dog"));
alphabets.forEach(s -> System.out.println(s));

This code will print every element of the list called alphabets. You can even replace lambda expression with method reference because we are passing the lambda parameter as it is to the
System.out.println() method as shown below:

 alphabets.forEach(System.out::println);
 
Now, let's see if you want to add comma between two elements than you can do so by using lambda parameters as shown in the following example

alphabets.forEach(s -> System.out.print(s + ","));

Btw, now you cannot use method reference now because we are doing something with lambda parameters. Let's see another example of forEach() method for doing filtering of elements.


filter and forEach() Example
One of the main features of Stream API is its capability to filter elements based upon some any condition. We have already seen glimpse of powerful feature of Stream API in my earlier post, how to use Stream API in Java 8, here we will see it again but in the context of forEach() method.

let's now only print elements which start with "a", following code will do that for you, startWith() is a method of String class, which return true if String is starting with String "a" or it will return false. Once list is filtered than forEach() method will print all elements starting with  String "a", as shown below:

alphabets.stream()
         .filter(s -> s.startsWith("a"))
         .forEach(System.out::println);
   

This is cool, right? You can read the code like cake, it's much easier than using Iterator or any other ways to loop over List in Java.

Now, let's filter out only which has length greater than 2, for this purpose we can use the length() function of String class:

alphabets.stream()
         .filter(s -> s.length() > 2)
         .forEach(System.out::println);


forEach() and map() Example
So far you have both basic and advanced example of using the forEach() method, first with simply iterating over each element and then along with using the filter() method, Let's see one more example of forEach() method along with the map() function, which is another key functionality of Stream API.

The map() method of Java 8 allows you to transform one type to another e.g. in our first example we are using map() to transform a list of String to a list of Integer where each element represents the length of String. Now, let's print length of each string using map() function:

alphabets.stream()
         .mapToInt(s -> s.length())
         .forEach(System.out::println);
   
That was fun, isn't it? how about the calculating sum of the length of all string? you can do so by using fold operations like sum() as shown in the following example:

alphabets.stream()
         .mapToInt(s -> s.length())
         .sum();

These were some of the common but very useful examples of Java 8's forEach() method, a new way to loop over List in Java. If you feeling nostalgist than don't forget to the journey of for loop in Java, a recap of for loop from JDK 1 to JDK 8.


Program to use forEach() function in Java 8
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Java Program to show How to use forEach() statement in Java8.
 * You can loop over a list, set or any collection using this
 * method. You can even do filtering and transformation and 
 * can run the loop in parallel.
 *
 * @author WINDOWS 8
 */
public class Java8Demo {

    public static void main(String args[]) {

       List<String> alphabets = new ArrayList<>(Arrays.asList("aa", "bbb", "cac", "dog"));
       
       // looping over all elements using Iterable.forEach() method
       alphabets.forEach(s -> System.out.println(s));
       
       // You can even replace lambda expression with method reference
       // because we are passing the lambda parameter as it is to the
       // method
       alphabets.forEach(System.out::println);
       
       // you can even do something with lambda parameter e.g. adding a comma
       alphabets.forEach(s -> System.out.print(s + ","));
       
       
       // There is one more forEach() method on Stream class, which operates
       // on stream and allows you to use various stream methods e.g. filter()
       // map() etc
       
       alphabets.stream().forEach(System.out::println);
       
       // let's now only print elmements which startswith "a"
       alphabets.stream()
               .filter(s -> s.startsWith("a"))
               .forEach(System.out::println);
       
       // let's filter out only which has length greater than 2
       alphabets.stream()
               .filter(s -> s.length() > 2)
               .forEach(System.out::println);

       
       // now, let's print length of each string using map()
       alphabets.stream()
               .mapToInt(s -> s.length())
               .forEach(System.out::println);
       
       // how about calculating sum of length of all string
       alphabets.stream()
               .mapToInt(s -> s.length())
               .sum();

    }

}



Important things to remember:

1) forEach() is a terminal operation, which means once calling forEach() method on stream, you cannot call another method. It will result in a runtime exception.

2) When you call forEach() on parallel stream, the order of iteration is not guaranteed, but you can ensure that ordering by calling forEachOrdered() method.

3) There are two forEach() method in Java 8, one defined inside Iterable and other inside java.util.stream.Stream class. If purpose of forEach() is just iteration then you can directly call it e.g. list.forEach() or set.forEach() but if you want to perform some operations e.g. filter or map then better first get the stream and then perform that operation and finally call forEach() method.

4) Use of forEach() results in readable and cleaner code.

Here are some advantages and benefits of Java 8 forEach() method over traditional for loop:

How to use forEach() method in Java 8? Examples


That's all about how to use forEach() in Java 8. By following these examples, you can easily get to speed with respect to using the forEach() method. It's perfect to be used along with stream and lambda expression, and allow you to write loop-free code in Java. Now, one task for you, how do you break? Does forEach() method allow you to break in between? If you know the answer posts as a comment.


Further Reading
  • Top 10 Java 8 Tutorials for Programmers (read here)
  • 5 good books to learn Java 8 from scractch (see here)
  • 20 Examples of new Date adn Time API of JDK 8 (examples)
  • How to read a file in just one line in Java 8? (solution)
  • 10 JDK 7 features to revise before starting with Java 8? (features)
  • Java SE 8 for Really Impatient by Cay S. Horstmann (see here)


No comments:

Post a Comment