Java 8 forEach example

In Java 8 and the introduction of the Stream class, we can call the forEach method to loop on all the elements of a List.

Syntax: o -> { /* action */ } );

It is recommended to use the forEach method, as it limits the scope of the local variable. This prevents bugs that would use the variable later in the code.


First the code creates a List of Persons and loops on each of them to display their first names. Then, it filters on the persons that are less than 40, and call the toString method for that subset of Persons.

Create the following java file:

import java.util.Arrays;
import java.util.List;

public class LambdaForEach {

	public static void main(String[] argv){
		List<Person> list = Arrays.asList( new Person( "Olivier", "Tech", Person.Sex.MALE, 35 ), 
				new Person( "Rick", "Tech", Person.Sex.MALE, 21 ), 
				new Person( "Joe", "Tech", Person.Sex.MALE, 45 ), 
				new Person( "Mike", "Tech", Person.Sex.MALE, 55 ) ); o -> { 
				System.out.println( "The person first name is " + o.getFirstName());
			.filter( p -> p.getAge() < 40 )
			.forEach( p -> { 
				System.out.println( p.toString() );
	static class Person {
		enum Sex {
		private String firstName;
		private String lastName;
		private int age;
		private Sex sex;
		public Person( String firstName, String lastName, Sex sex , int age ){
			this.firstName = firstName;
			this.lastName = lastName; = sex;
			this.age = age;
		public Sex getSex(){
			return sex;

		public int getAge(){
			return age;
		public String getFirstName(){
			return firstName;
		public String getLastName(){
			return lastName;
		public String toString(){
			return "["+firstName+", "+ lastName+", "+ sex+", "+age +"]";

The output will be:

The person first name is Olivier
The person first name is Rick
The person first name is Joe
The person first name is Mike
[Olivier, Tech, MALE, 35]
[Rick, Tech, MALE, 21]


Lambda Expressions

Recent Comments