- Java forEach
- Consumer interface
- Lambda expression
- Java forEach on Map
- Java forEach on Set
- Using forEach on Array
- Filtering a list
- IntConsumer, LongConsumer, DoubleConsumer
- Author
- Guide to Java Streams: forEach() with Examples
- forEach() on List
- forEach() on Map
- Free eBook: Git Essentials
- forEach() on Set
- Side-effects Vs Return Values
- Conclusion
- Java ArrayList forEach()
Java forEach
Java forEach tutorial shows how to use Java 8 forEach method. We work with consumers and demonstrate forEach on lists, map, and set collections.
The forEach method was introduced in Java 8. It provides programmers a new, concise way of iterating over a collection.
The forEach method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
void forEach(Consumer action);
This is the syntax of the forEach method.
Consumer interface
The Consumer interface is a functional interface (an interface with a single abstract method), which accepts a single input and returns no result.
@FunctionalInterface public interface Consumer
This is the definition of the Consumer interface.
package com.zetcode; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class JavaForEachListConsumer < public static void main(String[] args) < Listitems = new ArrayList<>(); items.add("coins"); items.add("pens"); items.add("keys"); items.add("sheets"); items.forEach(new Consumer() < @Override public void accept(String name) < System.out.println(name); >>); > >
In this example, we iterate over a list of strings with forEach . This syntax can be shortened with Java lambda expression.
Lambda expression
Lambda expressions are used primarily to define an inline implementation of a functional interface, i.e., an interface with a single method only. Lambda expression are created with the -> lambda operator.
package com.zetcode; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class JavaForEachListLambda < public static void main(String[] args) < Listitems = new ArrayList<>(); items.add("coins"); items.add("pens"); items.add("keys"); items.add("sheets"); items.forEach((String name) -> < System.out.println(name); >); > >
Here we have the same example. The lambda expression makes the example more concise.
Java forEach on Map
The following example uses forEach on a map.
package com.zetcode; import java.util.HashMap; import java.util.Map; public class JavaForEachMap < public static void main(String[] args) < Mapitems = new HashMap<>(); items.put("coins", 3); items.put("pens", 2); items.put("keys", 1); items.put("sheets", 12); items.forEach((k, v) -> < System.out.printf("%s : %d%n", k, v); >); > >
We have a map of string/integer pairs. With the forEach method, we iterate over the map and print its key/value pairs.
In the next example, we explicitly show the Consumer and the Map.Entry in code.
package com.zetcode; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; public class ForEachMap2 < public static void main(String[] args) < HashMapmap = new HashMap<>(); map.put("cups", 6); map.put("clocks", 2); map.put("pens", 12); Consumeraction = entry -> < System.out.printf("key: %s", entry.getKey()); System.out.printf(" value: %s%n", entry.getValue()); >; map.entrySet().forEach(action); > >
The example loops on a entry set, which is retrieved via entrySet .
Java forEach on Set
The following example uses forEach on a set.
package com.zetcode; import java.util.HashSet; import java.util.Set; public class JavaForEachSet < public static void main(String[] args) < Setbrands = new HashSet<>(); brands.add("Nike"); brands.add("IBM"); brands.add("Google"); brands.add("Apple"); brands.forEach((e) -> < System.out.println(e); >); > >
We have a set of strings. With the forEach method, we iterate over the set and print its values.
Using forEach on Array
The following example uses forEach on an array.
package com.zetcode; import java.util.Arrays; public class JavaForEachArray < public static void main(String[] args) < int[] nums = < 3, 4, 2, 1, 6, 7 >; Arrays.stream(nums).forEach((e) -> < System.out.println(e); >); > >
In the example, we have an array of integers. We use Arrays.stream method to transform the array into a stream. The forEach method then iterates over the elements and prints them to the console.
Filtering a list
We can easily filter our data before traversing them with forEach .
package com.zetcode; import java.util.ArrayList; import java.util.List; public class JavaForEachListFilter < public static void main(String[] args) < Listitems = new ArrayList<>(); items.add("coins"); items.add("pens"); items.add("keys"); items.add("sheets"); items.stream().filter(item -> (item.length() == 4)).forEach(System.out::println); > >
In this example, we filter a list of strings and print the filtered list to the console. Only strings having four characters are shown.
IntConsumer, LongConsumer, DoubleConsumer
Since Java 8, we have built-in consumer interfaces for primitive data types: IntConsumer , LongConsumer and DoubleConsumer .
package com.zetcode; import java.util.Arrays; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; import java.util.function.LongConsumer; public class JavaForEachConsSpec < public static void main(String[] args) < int[] inums = < 3, 5, 6, 7, 5 >; IntConsumer icons = i -> System.out.print(i + " "); Arrays.stream(inums).forEach(icons); System.out.println(); long[] lnums = < 13L, 3L, 6L, 1L, 8L >; LongConsumer lcons = l -> System.out.print(l + " "); Arrays.stream(lnums).forEach(lcons); System.out.println(); double[] dnums = < 3.4d, 9d, 6.8d, 10.3d, 2.3d >; DoubleConsumer dcons = d -> System.out.print(d + " "); Arrays.stream(dnums).forEach(dcons); System.out.println(); > >
In the example, we create the three types of consumers and iterate over them with forEach .
In this article we have presented the Java 8 forEach method. We have introduced consumers and used forEach on lists, maps, and set.
Author
My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.
Guide to Java Streams: forEach() with Examples
The forEach() method is part of the Stream interface and is used to execute a specified operation, defined by a Consumer .
The Consumer interface represents any operation that takes an argument as input, and has no output. This sort of behavior is acceptable because the forEach() method is used to change the program’s state via side-effects, not explicit return types.
Therefore, the best target candidates for Consumers are lambda functions and method references. It’s worth noting that forEach() can be used on any Collection .
forEach() on List
The forEach() method is a terminal operation, which means that after we call this method, the stream along with all of its integrated transformations will be materialized. That is to say, they’ll «gain substance», rather than being streamed.
Let’s generate a small list:
List list = new ArrayList(); list.add(1); list.add(2); list.add(3);
Traditionally, you could write a for-each loop to go through it:
for (Integer element : list) < System.out.print(element + " "); >
Alternatively, we can use the forEach() method on a Stream :
We can make this even simpler via a method reference:
list.stream().forEach(System.out::println);
forEach() on Map
The forEach() method is really useful if we want to avoid chaining many stream methods. Let’s generate a map with a few movies and their respective IMDB scores:
Map map = new HashMap(); map.put("Forrest Gump", 8.8); map.put("The Matrix", 8.7); map.put("The Hunt", 8.3); map.put("Monty Python's Life of Brian", 8.1); map.put("Who's Singin' Over There?", 8.9);
Now, let’s print out the values of each film that has a score higher than 8.4 :
map.entrySet() .stream() .filter(entry -> entry.getValue() > 8.4) .forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue()));
Forrest Gump: 8.8 The Matrix: 8.7 Who's Singin' Over There?: 8.9
Here, we’ve converted a Map to a Set via entrySet() , streamed it, filtered based on the score and finally printed them out via a forEach() . Instead of basing this on the return of filter() , we could’ve based our logic on side-effects and skipped the filter() method:
map.entrySet() .stream() .forEach(entry -> < if (entry.getValue() > 8.4) < System.out.println(entry.getKey() + ": " + entry.getValue()); > > );
Forrest Gump: 8.8 The Matrix: 8.7 Who's Singin' Over There?: 8.9
Finally, we can omit both the stream() and filter() methods by starting out with forEach() in the beginning:
map.forEach((k, v) -> < if (v > 8.4) < System.out.println(k + ": " + v); > >);
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Forrest Gump: 8.8 The Matrix: 8.7 Who's Singin' Over There?: 8.9
forEach() on Set
Let’s take a look at how we can use the forEach method on a Set in a bit more tangible context. First, let’s define a class that represents an Employee of a company:
public class Employee < private String name; private double workedHours; private double dedicationScore; // Constructor, Getters and Setters public void calculateDedication() < dedicationScore = workedHours*1.5; > public void receiveReward() < System.out.println(String .format("%s just got a reward for being a dedicated worker!", name)); > >
Imagining we’re the manager, we’ll want to pick out certain employees that have worked overtime and award them for the hard work. First, let’s make a Set :
Set employees = new HashSet(); employees.add(new Employee("Vladimir", 60)); employees.add(new Employee("John", 25)); employees.add(new Employee("David", 40)); employees.add(new Employee("Darinka", 60));
Then, let’s calculate each employee’s dedication score:
employees.stream().forEach(Employee::calculateDedication);
Now that each employee has a dedication score, let’s remove the ones with a score that’s too low:
Set regular = employees.stream() .filter(employee -> employee.getDedicationScore() 60) .collect(Collectors.toSet()); employees.removeAll(regular);
Finally, let’s reward the employees for their hard work:
employees.stream().forEach(employee -> employee.receiveReward());
And for clarity’s sake, let’s print out the names of the lucky workers:
System.out.println("Awarded employees:"); employees.stream().map(employee -> employee.getName()).forEach(employee -> System.out.println(employee));
After running the code above, we get the following output:
Vladimir just got a reward for being a dedicated worker! Darinka just got a reward for being a dedicated worker! Awarded employees: Vladimir Darinka
Side-effects Vs Return Values
The point of every command is to evaluate the expression from start to finish. Everything in-between is a side-effect. In this context, it means altering the state, flow or variables without returning any values.
Let’s take a look at the difference on another list:
List targetList = Arrays.asList(1, -2, 3, -4, 5, 6, -7);
This approach is based on the returned values from an ArrayList :
long result1 = targetList .stream() .filter(integer -> integer > 0) .count(); System.out.println("Result: " + result1);
And now, instead of basing the logic of the program on the return type, we’ll perform a forEach() on the stream and add the results to an AtomicInteger (streams operate concurrently):
AtomicInteger result2 = new AtomicInteger(); targetList.stream().forEach(integer -> < if (integer > 0) result2.addAndGet(1); >); System.out.println("Result: " + result2);
Conclusion
The forEach() method is a really useful method to use to iterate over collections in Java in a functional approach.
In certain cases, they can massively simplify the code and enhance clarity and brevity. In this article, we’ve gone over the basics of using a forEach() and then covered examples of the method on a List , Map and Set .
We’ve covered the difference between the for-each loop and the forEach() , as well as the difference between basing logic on return values versus side-effects.
Java ArrayList forEach()
The ArrayList forEach() method performs the specified Consumer action on each element of the List until all elements have been processed or the action throws an exception.
By default, actions are performed on elements taken in the order of iteration.
1. Internal Implementation of forEach()
As shown below, the method iterates over all list elements and calls action.accept() for each element. Here the action is an instance of Consumer interface.
@Override public void forEach(Consumer action) < Objects.requireNonNull(action); final int expectedModCount = modCount; @SuppressWarnings("unchecked") final E[] elementData = (E[]) this.elementData; final int size = this.size; for (int i=0; modCount == expectedModCount && i < size; i++) < action.accept(elementData[i]); >if (modCount != expectedModCount) < throw new ConcurrentModificationException(); >>
- Method parameter – The Consumer action to be performed for each element.
- Method returns – void.
- Method throws – ConcurrentModificationException and NullPointerException.
2. ArrayList forEach() Examples
2.1. Print All List Items to the Console
Let us begin with a very simple Java program that just prints each of the elements from the List. We can apply the same code for ArrayList class as well.
List list = Arrays.asList("A","B","C","D"); list.forEach(System.out::println);
2.2. Custom Consumer Actions
A Consumer implementation takes a single argument, and returns no value. We can also pass the custom actions we have created in other places.
For example, the following code iterates a list and prints the lowercase strings using the forEach() API.
Consumer action = x -> System.out.println(x.toLowerCase()); list.forEach(action);
We can pass the simple lambda expression inline, as well.
list.forEach(e -> System.out.println(e.toLowerCase()));
If there are more than one statement in the Consumer action then use the curly braces to wrap the statements.