In the tutorial, we show how to use Java 8 forEach()
method with Iterable (List + Map) and Stream.
I. Java 8 – forEach
1. forEach()
In Java 8, Iterable and Stream Interfaces provides a new method forEach() to iterate the elements.
import java.util.function.Consumer ... void forEach(Consumer<? super T> action) @FunctionalInterface public interface Consumer { void accept(T t); } |
2. How to use it?
2.1 Functional Interface Consumer
To use Java 8 forEach() method, we need defined a Functional Interface Consumer:
#1 -> create Functional Interface Consumer by anonymous inner class
List<Customer> customers = Arrays.asList(new Customer("Jack", "Davis", 25), new Customer("Mary", "Taylor", 37), ... customers.forEach(new Consumer<Customer>() { public void accept(Customer cust) { System.out.println(cust); } }); |
#2 -> Use Lambda Expression to create Functional Interface Consumer
List<Customer> customers = Arrays.asList(new Customer("Jack", "Davis", 25), new Customer("Mary", "Taylor", 37), ... Consumer<Customer> customerConsumer = (Customer c) -> System.out.println( String.format("firstName=%s, " + "lastName=%s" + ", age=%d" , c.firstName, c.lastName, c.age)); customers.forEach(customerConsumer); |
2.2 Lambda Expression + Method Reference
We can use shortcut syntax with Lambda Expression and Method Reference:
-> Use Lambda expression
customers.forEach(c -> System.out.println(c)); |
-> Use Method Reference:
customers.forEach(System.out::println); |
If Customer
class define a show()
method, we can use it with Method Reference:
public class Customer{ ... public void show() { System.out.println(toString()); } } customers.forEach(Customer::show); |
3. Java 8 forEach() with break + continue
forEach
does not work with break
statement. But we can use return
statement like a continue
in a for-each
.
customers.forEach(c -> { if(c.age <= 30) return; c.show(); }); |
4. Java 8 forEach() with Stream
4.1 List -> Stream -> forEach()
List<Customer> customers = Arrays.asList(new Customer("Jack", "Davis", 25), new Customer("Mary", "Taylor", 37), ... customers.stream().filter(c->c.age>30).forEach(System.out::println); |
4.2 Map -> Stream -> forEach()
Map<Customer, Address> personInfos = new HashMap<Customer, Address>(); personInfos.put(new Customer("Jack", "Davis", 25), new Address("NANTERRE CT", "77471")); personInfos.put(new Customer("Mary", "Taylor", 37), new Address("W NORMA ST", "77009")); personInfos.entrySet().stream() .filter(person -> person.getKey().age >= 25) .forEach(person -> System.out.println(String.format( "%s lives at '%s'", person.getKey().firstName, person.getValue().street))); |
II. SourceCode
1. Data models
package com.javasampleapproach.java8.foreach; public class Address{ String street; String postcode; public Address(String street, String postcode){ this.street = street; this.postcode = postcode; } } package com.javasampleapproach.java8.foreach; public class Customer{ String firstName; String lastName; Integer age; public Customer(String firstName, String lastName, Integer age){ this.firstName = firstName; this.lastName = lastName; this.age = age; } @Override public String toString() { String str = String.format("firstName = %s, lastName = %s, age = %d", firstName, lastName, age); return str; } public void show() { System.out.println(toString()); } } |
2. Java 8 forEach() with List + Stream
package com.javasampleapproach.java8.foreach; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; public class Java8ForEachList { public static void main(String[] args) { List<Customer> customers = Arrays.asList(new Customer("Jack", "Davis", 25), new Customer("Mary", "Taylor", 37), new Customer("Peter", "Thomas",17), new Customer("Amos", "Nelson",23), new Customer("Craig", "White",45), new Customer("Laura", "Lewis", 32), new Customer("Steven", "Harris", 39), new Customer("Paul", "Moore", 18), new Customer("Mary", "Cook", 61)); // --> 1. Use Functional Consumer Consumer<Customer> customerConsumer = (Customer c) -> System.out.println( String.format("firstName=%s, " + "lastName=%s" + ", age=%d" , c.firstName, c.lastName, c.age)); System.out.println("--> 1. Use Consumer"); customers.forEach(customerConsumer); /* firstName=Jack, lastName=Davis, age=25 firstName=Mary, lastName=Taylor, age=37 firstName=Peter, lastName=Thomas, age=17 firstName=Amos, lastName=Nelson, age=23 firstName=Craig, lastName=White, age=45 firstName=Laura, lastName=Lewis, age=32 firstName=Steven, lastName=Harris, age=39 firstName=Paul, lastName=Moore, age=18 firstName=Mary, lastName=Cook, age=61 */ // --> 2. Use Lambda Expression System.out.println("--> 2. Use Lambda Expression"); customers.forEach(c -> System.out.println(c)); // --> 3. Use Method Reference // ----> 3.1 System.out.println("--> 3. Use Method Reference"); System.out.println("----> 3.1"); customers.forEach(System.out::println); // or // ----> 3.2 System.out.println("----> 3.2"); customers.forEach(Customer::show); // ----> 4. forEach with return System.out.println("----> 4"); customers.forEach(c -> { if(c.age <= 30) return; c.show(); }); /* firstName = Mary, lastName = Taylor, age = 37 firstName = Craig, lastName = White, age = 45 firstName = Laura, lastName = Lewis, age = 32 firstName = Steven, lastName = Harris, age = 39 firstName = Mary, lastName = Cook, age = 61 */ // --> 5. (List -> Stream) System.out.println("--> 5. ForEach With Stream"); customers.stream().filter(c->c.age>30).forEach(System.out::println); /* firstName = Mary, lastName = Taylor, age = 37 firstName = Craig, lastName = White, age = 45 firstName = Laura, lastName = Lewis, age = 32 firstName = Steven, lastName = Harris, age = 39 firstName = Mary, lastName = Cook, age = 61 */ } } |
3. Java 8 forEach() with Map + Stream
package com.javasampleapproach.java8.foreach; import java.util.HashMap; import java.util.Map; public class Java8ForEachMap { public static void main(String[] args) { Map<Customer, Address> personInfos = new HashMap<Customer, Address>(); personInfos.put(new Customer("Jack", "Davis", 25), new Address("NANTERRE CT", "77471")); personInfos.put(new Customer("Mary", "Taylor", 37), new Address("W NORMA ST", "77009")); personInfos.put(new Customer("Peter", "Thomas",17), new Address("S NUGENT AVE", "77571")); personInfos.put(new Customer("Amos", "Nelson",23), new Address("E NAVAHO TRL", "77449")); personInfos.put(new Customer("Craig", "White",45), new Address("AVE N", "77587")); System.out.println("--> ForEach Map"); personInfos.forEach((customer, address) -> { if(customer.age >= 25) { System.out.println(String.format("%s lives at '%s'", customer.firstName, address.street)); } }); /* Jack lives at 'NANTERRE CT' Craig lives at 'AVE N' Mary lives at 'W NORMA ST' */ System.out.println("--> ForEach (Map -> Stream)"); personInfos.entrySet().stream() .filter(person -> person.getKey().age >= 25) .forEach(person -> System.out.println(String.format( "%s lives at '%s'", person.getKey().firstName, person.getValue().street))); /* Jack lives at 'NANTERRE CT' Craig lives at 'AVE N' Mary lives at 'W NORMA ST' */ } } |
Last updated on April 13, 2019.