Lambda List Stream Filter

Lambda List Stream Filter

Java 8 Lambda expression is very useful which minimize multiple lines of code into single line and in this example you will see how to filter the list based on certain condition.

  • LamdaStreamFilter.java:
package com.javahonk;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class LamdaStreamFilter {

	public static void main(String[] args) {
		
		List<Person> persons = new ArrayList<Person>();
		persons.add(new Person("first name", "last name", 35));
		persons.add(new Person("first name2", "last name2", 45));
		persons.add(new Person("first name2", "last name2", 55));
		
		//old way
		
		for (Person person2 : persons) {
			if (person2.getAge() <= 45) {
				//put in filter list
			}
		}
		
		//New Lambda expression
		//Get new filtered list based on age 
		List<Person> SinglefilteredList = persons.stream().filter(person -> person.getAge() <= 45).collect(Collectors.toList());
		
		printFilteredList(SinglefilteredList);

		//Get new filtered list based on age with OR condition
		List<Person> ORfilteredList = persons.stream().filter(person -> person.getAge() == 45
						|| person.getAge() == 55).collect(Collectors.toList());
		
		printFilteredList(ORfilteredList);
		
		
	}
	
	private static void printFilteredList(List<Person> filteredList){
		
		filteredList.forEach(person -> {
			System.out.println(person.getFirstName());
			System.out.println(person.getLastName());
			System.out.println(person.getAge());
			System.out.println("---------------");
		});
	}

}

class Person {
	
	private String firstName;
	private String lastName;
	private Integer age;
	
	public Person(String firstName, String lastName, Integer age) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}

	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public Integer getAge() {
		return age;
	}
	
}
  • Output:

Lambda List Stream Filter

  • For more information please visit Oracle documentation here

Leave a Reply

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