Java Stream filter() with examples

 162 total views,  3 views today

Welcome to Java 8 series. In this tutorial, you will learn about the Java Stream filter with brief examples.

Stream filter() is an intermediate operation and it belongs to the Stream interface.

Java stream 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.

Since filter() is an intermediate operation it will have two characteristics

  1. filter() is a lazy loading operation. This means data will only filter when a terminal operation is invoked on the stream.
  2. filter() operation on a stream will always create a new stream output.

Let us now see a few examples of Java 8 stream filter()

Let us create a List

List<String> list = new ArrayList<>();
list.add("apple");
list.add("orange");
list.add("banana");
list.add("Guava");
list.add("cherry");

Now I want to filter only “Guava” from the list. After filtering the list, the output should only have “Guava”. Let us see how to do in Java 8 Stream filter.

Existing way of filtering a collection in Java

In below example, I have iterated over the list and checked if each item is equal to Guava. If the condition matches, I have created a new output list and added Guava to the new list.

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");
        
        List<String> output = new ArrayList<>();
        for(String str : list) {
            if (str.equalsIgnoreCase("Guava"))
            {
                output.add(str);
            } 
        }
     }
}

Using Java Stream filter example

public class StaticReference
{
    public static void main(String[] args)
    {
        //Create a list of Strings
        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);
		
	}
}

Output

Guava

In the above example, A lambda expression is passed to the filter function of the List and corresponding predicate validated.

Simplified Java Stream filter example

public class StaticReference
{
    public static void main(String[] args)
    {
       //Create a list of Strings
        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);
    }
}

Output

Guava

Java Stream filter Object example

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;
    }

}

In the below code, I have used filter() operation on the list of students to filter students whose age is greater than or equal to 30 and less than equal to 38.

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() >= 3 && student.getAge() <= 38))
            .forEach(System.out::println);
    }
}

Output

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

Conclusion

Java Stream filter() operation is mainly used for filtering stream elements. Filter() will always create a new stream and it is lazily evaluated.

References : Official documentation

Thanks for reading. Please a comment and give us a thumbs up! ๐Ÿ™‚

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!.