Java 8 Stream filter examples

Java 8 Stream filter
In this post,  we are going to see about Java 8 Stream filter example.
You can convert list or array to stream very easily and perform various operations on top of it.Java 8 Stream provides various methods such as map,  filter, reduce etc.
Let’s see more about Java 8 Stream filter method.

Java 8 Stream filter

As name suggests, filter method is used to filter stream on basis of criterion. You can pass lambda expressions to filter method but it should always return a boolean value. We have already seen how to pass Predicate object to filter method to filter a collection.
Lets understand more with help of example: 
Lets say you have Student class as below:

package org.arpit.java2blog;

public class Student {

    private int id;
    private String name;
    private String gender;
    private int age;

    public Student(int id, String name, String gender, int age) {
        super();
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.age = age;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", gender=" + gender + ", age=" + age + "]";
    }
}

Lets say you have list of student objects in studentList and you need to filter all male students.
You can do it with the help of Stream with below code:

// Filter all male students
List maleStudents=studentList.stream()
.filter(s-> s.getGender().equalsIgnoreCase("M") )
.collect(Collectors.toList());
System.out.println("Male students are :"+maleStudents);

Here we have used stream‘s filter method to filter list and then collect the result to another list with Collectors.toList().

Java 8 filter,findAny or orElse method

You can use stream’s filter method to filter list and use findAny and orElse method based on conditions.
For example:You want to filter Student with name John, if you do not find it in the list then return null.

// Filer based on name
Student student=studentList.stream()
.filter(s-> s.getName().equalsIgnoreCase("John"))
.findAny()
.orElse(null); 
System.out.println("Student with Name john :"+student);

Lets create a main class as below:

package org.arpit.java2blog;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Java8StreamFilterExamples {

    public static void main(String[] args)
    {   
        List studentList=createStudentList();   

        // Filter all male students
        List maleStudents=studentList.stream()
                .filter(s>s.getGender().equalsIgnoreCase("M"))
                .collect(Collectors.toList());
        System.out.println("Male students are :"+maleStudents);

                // Filter based on name
        Student student=studentList.stream()
                .filter(s-> s.getName().equalsIgnoreCase("John"))
                .findAny()
                .orElse(null); 
        System.out.println("Student with Name john :"+student);
    }

    public static List createStudentList()
    {
        List studentList=new ArrayList();
        Student s1=new Student(1, "Arpit", "M", 19);
        Student s2=new Student(2, "John", "M", 17);
        Student s3=new Student(3, "Mary", "F", 14);
        Student s4=new Student(4, "Martin", "M", 21);
        Student s5=new Student(5, "Monica", "F", 16);
        Student s6=new Student(6, "Ally", "F", 20);

        studentList.add(s1);
        studentList.add(s2);
        studentList.add(s3);
        studentList.add(s4);
        studentList.add(s5);
        studentList.add(s6);
        return studentList;
    }
}

When you run above program, you will get below output:

Male students are :[Student [id=1, name=Arpit, gender=M, age=19], Student [id=2, name=John, gender=M, age=17], Student [id=4, name=Martin, gender=M, age=21]]
Student with Name john :Student [id=2, name=John, gender=M, age=17]

Let me know if you need more examples for Stream‘s filter method.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.