Java 8 forEach Examples
- schick09
- Feb 21, 2024
- 3 min read
Updated: Apr 25, 2024
In our last blog post, we looked at creating and invoking Consumer functional interfaces. There are many components in the Java language that take a Consumer functional interface as an argument. In today's post we will examine the Iterable class 'forEach' method to illustrate.
For this example, we created a simple pojo called VacationProperty. VacationProperty objects have 5 attributes describing the amenties found at the given vacation property. These include the name of the property, along with a series of booleans indicating whether or not the property has parking, a restaurant, a pool, and/or spa.
We will demonstrate with 3 examples, ordered from most concise to least concise (ie, most 'wordy').
In each example, we first create a List<VacationProperty> populated with static values:
private static final List<VacationProperty> LIST_OF_PROPERTIES = asList(
new VacationProperty("Marriot Marquis",true,false,true,true),
new VacationProperty("Intercontinental Monterey",false,false,true,true),
new VacationProperty("Embassy Suites Peoria",true,true,true,true));
Our first example calls 'forEach' on the List itself, passing in a Consumer implementation that we have created called VacationPropertyConsumer.
This works because List is an Iterable, and Iterable has a method called forEach that takes a Consumer implementation.
As you may remember from our prior blog post, the Consumer interface has one method called 'accept' that must be implemented.
Here is the implementation of the VacationPropertyConsumer class:
package funwithjava8foreach;
import java.util.function.Consumer;
public class VacationPropertyConsumer implements Consumer<VacationProperty> {
@Override
public void accept(VacationProperty vacationProperty) {
StringBuilder sb = new StringBuilder(vacationProperty.getName())
.append(" has the following amenities: ");
if (vacationProperty.isParking()){
sb.append(" Parking ");
}
if (vacationProperty.isPool()){
sb.append(" Pool ");
}
if (vacationProperty.isRestaurant()){
sb.append(" Restaurant ");
}
if (vacationProperty.isSpa()){
sb.append(" Spa ");
}
vacationProperty.setSummary(sb.toString());
System.out.println(vacationProperty.getSummary());
}
}
The following code provides a concise example of iterating through each element in the List and calling the 'accept' method of the Consumer interface to create and print a summary of that property's amenities:
public static void firstExample(){
LIST_OF_PROPERTIES.forEach(new VacationPropertyConsumer());
}
As we all know, there is more than one way to implement the same logic. Instead of creating a separate class that implements the Consumer interface, you can always create an anonymous inner class that overrides the 'accept' method inline as shown below.
Because the Consumer interface only has one method to override, you can use functional syntax to create an implementation of the Consumer interface inline:
public static void secondExample(){
Consumer<VacationProperty> printListOfAmenities =
(property) -> {
StringBuilder sb = new StringBuilder(property.getName())
.append(" has the following amenities: ");
if (property.isParking()){
sb.append(" Parking ");
}
if (property.isPool()){
sb.append(" Pool ");
}
if (property.isRestaurant()){
sb.append(" Restaurant ");
}
if (property.isSpa()){
sb.append(" Spa ");
}
property.setSummary(sb.toString());
System.out.println(property.getSummary());
};
LIST_OF_PROPERTIES.forEach(printListOfAmenities);
}
Here's a longer form version of the same logic. This is less concise but implements the same functionality as the examples above.
public static void thirdExample() {
LIST_OF_PROPERTIES.forEach(new Consumer<VacationProperty>() {
public void accept(VacationProperty vacationProperty) {
StringBuilder sb = new StringBuilder(vacationProperty.getName())
.append(" has the following amenities: ");
if (vacationProperty.isParking()){
sb.append(" Parking ");
}
if (vacationProperty.isPool()){
sb.append(" Pool ");
}
if (vacationProperty.isRestaurant()){
sb.append(" Restaurant ");
}
if (vacationProperty.isSpa()){
sb.append(" Spa ");
}
vacationProperty.setSummary(sb.toString());
System.out.println(vacationProperty.getSummary());
}
});
}
And finally, here's an example of the same code above refactored to use the magic of lambda expressions to instantiate the Consumer functional interface implementation.
public static void fourthExample() {
LIST_OF_PROPERTIES.forEach((vacationProperty) -> {
StringBuilder sb = new StringBuilder(vacationProperty.getName())
.append(" has the following amenities: ");
if (vacationProperty.isParking()){
sb.append(" Parking ");
}
if (vacationProperty.isPool()){
sb.append(" Pool ");
}
if (vacationProperty.isRestaurant()){
sb.append(" Restaurant ");
}
if (vacationProperty.isSpa()){
sb.append(" Spa ");
}
vacationProperty.setSummary(sb.toString());
System.out.println(vacationProperty.getSummary());
});
}
Here's a link to our GitHub location to access this code example:

Comments