Here is java 8 stream filter example like single filter, multiple filter, filter with or condition, filter with function references, find first element using filter, find any and all match

Example 1: Stream filter + Collect to List

Here filter for Developer and collect data to List <Employee>. List will contains only developer employees, collect() method will collect data to List and return List. Using foreach print developers which shown in output.

java.util.List<Employee> employees = Employee.getEmployee();

        java.util.List<Employee> developers = employees.stream()
                .filter(employee -> employee.getDesignation().equals("Developer"))               // Find for designation is Developer
                .collect(java.util.stream.Collectors.toList());                                 // Collect result to List

        developers.forEach(developer -> {
            System.out.println(developer);
        });

Output:

1 : Bob : Male : Developer
4 : Bat : Male : Developer
5 : Jolly : Female : Developer
6 : Bobby : Female : Developer

Example 2: Stream multiple filter

Here, Stream with multiple filter, Filters are always with AND condition. collect() will collect those data which satisfied both condition in filter.

java.util.List<Employee> employees = Employee.getEmployee();

java.util.List<Employee> developersAndMale = employees.stream()
        .filter(employee -> employee.getDesignation().equals("Developer"))       // Find for designation is Developer
        .filter(employee -> employee.getGender().equals("Male"))                 // find for Gender is Male
        .collect(java.util.stream.Collectors.toList());                          // Collect result to List

developersAndMale.forEach(employee -> {
    System.out.println(employee);
});

Output:

1 : Bob : Male : Developer
4 : Bat : Male : Developer

Example 3: Stream filter with OR Condition

If filter require OR condition than we can write like bellow example, Both condition in single filter with OR operation. collect() method will collect data to List.

java.util.List<Employee> employees = Employee.getEmployee();
        java.util.List<Employee> developers = employees.stream().
                filter(employee -> (employee.getDesignation().equals("Developer") || employee.getDesignation().equals("CEO")))   // Find for Developer OR CRO
                .collect(Collectors.toList());                                                                                   // Collect result to List
        developers.forEach(developer -> {
            System.out.println(developer);
        });

 Output:

1 : Bob : Male : Developer
3 : John : Male : CEO
4 : Bat : Male : Developer
5 : Jolly : Female : Developer
6 : Bobby : Female : Developer

Example 4: Stream Filter with Function References

java 8 filters also support method or function references like ClassName::MethodName, method must return boolean values.

public static void example1(){
       java.util.List<Employee> employees = Employee.getEmployee();
       java.util.List<Employee> developers = employees.stream()
               .filter(FilterMultipleFilterCondition::getFemaleDevelopers)            // Calling Reference Method
               .collect(java.util.stream.Collectors.toList());
       developers.forEach(developer -> {
           System.out.println(developer);
       });
   }
   
   public static boolean getFemaleDevelopers(Employee employee){
       return (employee.getDesignation().equals("Developer") ||  employee.getGender().equals("Female"));
   }

 Output:

1 : Bob : Male : Developer
4 : Bat : Male : Developer
5 : Jolly : Female : Developer
6 : Bobby : Female : Developer

Example 5: Stream Filter + findFirst()

findFirst() return first result from filter. findFirst() return Optional with element if no element found than it return Empty Optional.

java.util.List<Employee> employees = Employee.getEmployee();
        Optional<Employee> employeeOptional = employees.stream().filter(employee -> {
            return employee.getDesignation().equals("Developer");
        }).findFirst();     // Its will find first employee Developer and return Optional

        if (employeeOptional.isPresent()) {  // check if find any developer
            System.out.println(employeeOptional.get());
        }

 Output:

1 : Bob : Male : Developer

Example 6: Stream Filter + anyMatch()

Returns whether any elements of this stream match the provided Predicate. May not evaluate the predicate on all elements if not necessary for determining the result. if any elements of the stream match the provided predicate, otherwise false.

java.util.List<Employee> employees = Employee.getEmployee();
        boolean containsEmmployeeStartWithB = employees.stream()
                                                       .anyMatch(employee -> {   // result is true if any employee name start with B
                                                           return employee.getName().startsWith("B");
                                                       });
        System.out.print("Is any Employee Name Start with B : " + containsEmmployeeStartWithB);

 Output:

Is any Employee Name Start with B : true

Example 7: Stream Filter + allMatch()

Returns whether all elements of this stream match the provided Predicate. if either all elements of the stream match the provided predicate or the stream is empty, otherwise false.

java.util.List<Employee> employees = Employee.getEmployee();
       boolean isAllEmplyeeGreaterThan15 = employees.stream()
                                                      .allMatch(employee -> {   // result if all employee number greater than 15
                                                          return employee.getNo() < 15;
                                                      });
       System.out.println("Is All Employee Number Greater than 15 : " + isAllEmplyeeGreaterThan15);

Output:

Is All Employee Number Greater than 15 : true

 

 Employee.java

package com.javadeveloperzone;

import java.util.ArrayList;

/**
 * Created by JavaDeveloperZone on 29-04-2017.
 */
public class Employee {
    private int no;
    private String name;
    private String designation;
    private String gender;

    public Employee(int no, String name, String designation, String gender) {
        this.no = no;
        this.name = name;
        this.designation = designation;
        this.gender = gender;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

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

    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }

    public String getGender() {
        return gender;
    }

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

    @Override
    public String toString() {
        return this.no + " : " + this.name + " : " + gender + " : " + designation;
    }

    public static java.util.List<Employee> getEmployee() {
        java.util.List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1, "Bob", "Developer", "Male"));
        employees.add(new Employee(2, "Joy", "Sr. Developer", "Male"));
        employees.add(new Employee(3, "John", "CEO", "Male"));
        employees.add(new Employee(4, "Bat", "Developer", "Male"));
        employees.add(new Employee(5, "Jolly", "Developer", "Female"));
        employees.add(new Employee(6, "Bobby", "Developer", "Female"));
        return employees;
    }
}

 References:

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No
Tags: ,

Leave a Reply

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