Java 8 forEach – with Iterable (List + Map) and Stream

java-8-for-each-examples

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 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 customers = Arrays.asList(new Customer("Jack", "Davis", 25),
											new Customer("Mary", "Taylor", 37),
											...
											
customers.forEach(new Consumer() {
	public void accept(Customer cust) {
    	System.out.println(cust);
	}
});

#2 -> Use Lambda Expression to create Functional Interface Consumer

List customers = Arrays.asList(new Customer("Jack", "Davis", 25),
											new Customer("Mary", "Taylor", 37),
											...
											
Consumer 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 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 personInfos = new HashMap();

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 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 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 personInfos = new HashMap();
		
		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'
		 */
	}
}

2 thoughts on “Java 8 forEach – with Iterable (List + Map) and Stream”

  1. Thanks for another informative site. Where else could I get that kind of information written in such a perfect way? I’ve a project that I’m just now working on, and I’ve been on the look out for such information.

Leave a Reply

Your email address will not be published. Required fields are marked *