5 ways to use Java stream filter()

 177 total views,  1 views today

Welcome to Java 8 series. In this tutorial, you will learn about 5 ways to use java stream filter().

filter() is a part of Stream pipeline and it is an intermediate operation

filter() belongs to the Stream interface.

filter() operation allows us to apply filter conditions on the stream data. A filter will accept a function (a Lambda expression or a Predicate interface) which evaluates each item of the stream against the given boolean or predicate condition.

Let us now see 5 ways to use java stream filter() operation

Filter each item using Lambda with if-else

public class StaticReference
{
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<>();
        list.add("apple");
        list.add("orange");
        list.add("banana");
        list.add("Guava");
        list.add("cherry");
        
        // Filter each item using Lambda with if else
        list.stream().filter(item -> {
            if (item.equalsIgnoreCase("Guava"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }).forEach(System.out::println);
     }
}

Filter each item using Lambda simplified if-else

public class StaticReference
{
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<>();
        list.add("apple");
        list.add("orange");
        list.add("banana");
        list.add("Guava");
        list.add("cherry");

        // Filter each item using Lambda simplified if else
        list.stream().filter(item -> 
          item.equalsIgnoreCase("Guava")).forEach(System.out::println);
    }
}

Filter using method reference

public class StaticReference
{
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<>();
        list.add("apple");
        list.add("orange");
        list.add("banana");
        list.add("Guava");
        list.add("cherry");

        // Filter using method reference      
       list.stream().filter(StaticReference::check)
                    .forEach(System.out::println);
     }


    static Boolean check(String item)
    {
        return item.equalsIgnoreCase("Guava");
    }
}

Filter using Predicate interface with method reference

public class StaticReference
{
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<>();
        list.add("apple");
        list.add("orange");
        list.add("banana");
        list.add("Guava");
        list.add("cherry");

        // Filter using Predicate interface with method reference
        Predicate<String> predicate = StaticReference::check;
        list.stream().filter(predicate).
                     forEach(System.out::println);
    }
   
    static Boolean check(String item)
    {
        return item.equalsIgnoreCase("Guava");
    }
}

Filter using Predicate interface with lambda expression

public class StaticReference
{
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<>();
        list.add("apple");
        list.add("orange");
        list.add("banana");
        list.add("Guava");
        list.add("cherry");

        // Filter using Predicate interface with lambda expression
        Predicate<String> predicateLambda = item -> 
                      item.equalsIgnoreCase("Guava");
        
       list.stream().filter(predicateLambda)
                    .forEach(System.out::println);
    }
}

Output for each example

Guava

Java Stream filter() objects

class Student
{

    String name;
    int age;
    String country;

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

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

    public String getName()
    {
        return name;
    }

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

    public int getAge()
    {
        return age;
    }

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

    public String getCountry()
    {
        return country;
    }

    public void setCountry(String country)
    {
        this.country = country;
    }

}
public class StaticReference
{
    public static void main(String[] args)
    {
        Student std1 = new Student("Raj", 27, "Canada");
        Student std2 = new Student("John wick", 32, "Netherlands");
        Student std3 = new Student("Peter", 33, "Ukraine");
        Student std4 = new Student("Mark", 54, "Australia");

        List<Student> listOfStudents = new ArrayList<Student>();
        listOfStudents.add(std1);
        listOfStudents.add(std2);
        listOfStudents.add(std3);
        listOfStudents.add(std4);

        listOfStudents.stream().filter(student -> 
                (student.getAge() >= 30  && student.getAge() <= 38))
               .forEach(System.out::println);
    }
}

Output

Student [name=John wick, age=32, country=Netherlands]
Student [name=Peter, age=33, country=Ukraine]

Complete Example

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class StaticReference
{
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<>();
        list.add("apple");
        list.add("orange");
        list.add("banana");
        list.add("Guava");
        list.add("cherry");
        
        //Usual way to filter a list
        List<String> output = new ArrayList<>();
        for(String str : list) {
            if (str.equalsIgnoreCase("Guava"))
            {
                output.add(str);
            } 
        }

        // Filter each item using Lambda with if else
        list.stream().filter(item -> {
            if (item.equalsIgnoreCase("Guava"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }).forEach(System.out::println);

        // Filter each item using Lambda simplified if else
        list.stream().filter(item -> 
        item.equalsIgnoreCase("Guava")).forEach(System.out::println);

        // Filter using method reference
        list.stream().filter(StaticReference::check).
                forEach(System.out::println);

        // Filter using Predicate interface with method reference
        Predicate<String> predicate = StaticReference::check;
        list.stream().filter(predicate)
                     .forEach(System.out::println);

        // Filter using Predicate interface with lambda expression
        Predicate<String> predicateLambda = item -> 
           item.equalsIgnoreCase("Guava");
        list.stream().filter(predicateLambda).
                   forEach(System.out::println);

        Student std1 = new Student("Raj", 27, "Canada");
        Student std2 = new Student("John wick", 32, "Netherlands");
        Student std3 = new Student("Peter", 33, "Ukraine");
        Student std4 = new Student("Mark", 54, "Australia");

        List<Student> listOfStudents = new ArrayList<Student>();
        listOfStudents.add(std1);
        listOfStudents.add(std2);
        listOfStudents.add(std3);
        listOfStudents.add(std4);

        listOfStudents.stream().filter(student -> 
           (student.getAge() >= 30 && student.getAge() <= 38))
           .forEach(System.out::println);
    }

    static Boolean check(String item)
    {
        return item.equalsIgnoreCase("Guava");
    }

}

class Student
{

    String name;
    int age;
    String country;

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

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

    public String getName()
    {
        return name;
    }

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

    public int getAge()
    {
        return age;
    }

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

    public String getCountry()
    {
        return country;
    }

    public void setCountry(String country)
    {
        this.country = country;
    }

}

Output

Guava
Guava
Guava
Guava
Guava
Student [name=John wick, age=32, country=Netherlands]
Student [name=Peter, age=33, country=Ukraine]

Hope this article helped. Please leave a comment and give us a thumbs up!.

ReferencesOfficial documentation

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.