Filter Java Collection using Java 8 Lambda & Stream Filter - Java @ Desk

Wednesday, November 1, 2017

Filter Java Collection using Java 8 Lambda & Stream Filter

Filter Java Collection using Java 8 Lambda & Stream Filter

In this post, we will learn how to filter a list based on certain criteria. If we have a list of objects and we need a filtered list based on certain condition, then prior to Java 8 we need to iterate through the list and apply if conditions and get each object to add in the temporary list.

In Java 8, stream & filter operations using Lambda expressions helps to get the filtered list in a single statement itself.

Filter a stream of data for a given criteria and perform collect operations to get the collection of objects for the given criteria.

Below is the Java example for the same. There is a list of Person object and filter is applied to get all the persons where age of a person is greated than 18.

package com.pojo;

public class Person {

 private String id;

 private String name;

 private String address;

 private int age;

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }
}


package com.lambda;

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

import com.pojo.Person;

public class FilterListLambda {

 public static void main(String args[]) {

  List<Person> persons = new ArrayList<>();

  Person person = new Person();
  person.setAge(20);
  persons.add(person);

  Person personOne = new Person();
  personOne.setAge(25);
  persons.add(personOne);

  Person personTwo = new Person();
  personTwo.setAge(32);
  persons.add(personTwo);

  Person personThree = new Person();
  personThree.setAge(14);
  persons.add(personThree);

  // Find all persons where age greater than 18 using traditional For Loop

  List<Person> personsAgeGreaterThan18 = new ArrayList<>();

  for (Person tempPerson : persons) {
   if (tempPerson.getAge() > 18) {
    personsAgeGreaterThan18.add(tempPerson);
   }
  }

  // Using Java 8 Lambda & Streams

  personsAgeGreaterThan18 = persons.stream().filter(p -> p.getAge() > 18).collect(Collectors.toList());
 }
}








No comments:

Post a Comment