Wednesday, March 20, 2024

Java Stream - filter() With Examples

In this tutorial you will see some examples of filter() method in Java Stream API. filter() method is used to filter out some elements based on the passed condition and the remaining elements, that satisfy the condition, are returned as a new Stream.


filter() in Java

filter() in Java stream is an intermediate operation and its syntax is as given below-

Stream<T> filter(Predicate<? super T> predicate)

Here Predicate, which is a functional interface, is used to pass the condition that is used to filter out elements. Since Predicate is a functional interface so it is usually implemented as a lambda expression.

filter method Java examples

1. Let’s start with a simple example where we have a List of names and you want to display only those names that doesn’t start with ‘A’.

import java.util.Arrays;
import java.util.List;

public class FilterDemo {

  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Amit", "Ashok", "Manish", "Rajat");    
    nameList.stream()
        .filter(n -> !n.startsWith("A")) // Predicate implementation
        .forEach(System.out::println);
  }
}

Output

Ram
Manish
Rajat

2. If you want to store the results in another List then you can use collect method along with filter.

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

public class FilterDemo {

  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Amit", "Ashok", "Manish", "Rajat");    
    List<String> filteredList = nameList.stream()
        .filter(n -> !n.startsWith("A")) // Predicate implementation
        .collect(Collectors.toList());
    System.out.println("Result- " + filteredList);
  }
}

Output

Result- [Ram, Manish, Rajat]

Using filter() method with custom objects

For this Java Stream filter() method example we’ll use Employee class which is as given here.

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
}

3. Using filter() method to get the count of employees having salary >= 10000

import java.util.Arrays;
import java.util.List;

public class FilterDemo {

  public static void main(String[] args) {
     List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                 new Employee("E002", 35, "Shelly", 'F', 7000), 
                 new Employee("E003", 24, "Mark", 'M', 9000), 
                 new Employee("E004", 37, "Rani", 'F', 10000),
                 new Employee("E005", 32, "Anuj", 'M', 12000));  
    long count = empList.stream()
        .filter(e -> e.getSalary() >= 10000)
        .count();
    System.out.println("Employees with salary >= 10000: " + count);
  }
}

Output

Employees with salary >= 10000: 2

4. Get the list of female employees.

public class FilterDemo {

  public static void main(String[] args) {
     List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                 new Employee("E002", 35, "Shelly", 'F', 7000), 
                 new Employee("E003", 24, "Mark", 'M', 9000), 
                 new Employee("E004", 37, "Rani", 'F', 10000),
                 new Employee("E005", 32, "Anuj", 'M', 12000));  
     List<String> nameList = empList.stream()
        .filter(e -> (e.getGender() == 'F'))
        .map(Employee :: getName)
        .collect(Collectors.toList());
    System.out.println("Employee List: " + nameList);
  }
}

Output

Employee List: [Shelly, Rani]

filter() with multiple conditions

You can also combine several conditions by using conditional operators and(&&), or(||). For example if you want to get the list of female employees making more than 10000.

public class FilterDemo {

  public static void main(String[] args) {
     List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                 new Employee("E002", 35, "Shelly", 'F', 7000), 
                 new Employee("E003", 24, "Mark", 'M', 9000), 
                 new Employee("E004", 37, "Rani", 'F', 11000),
                 new Employee("E005", 32, "Anuj", 'M', 12000), 
                 new Employee("E006", 28, "Amy", 'F', 14000));  
     List<Employee> nameList = empList.stream()
        .filter(e -> (e.getGender() == 'F') && (e.getSalary() > 10000))
        .collect(Collectors.toList());
     
     for(Employee e : nameList) {
       System.out.println("Employee Name: " + e.getName() 
         + " Salary: " + e.getSalary());
     }
  }
}

Output

Employee Name: Rani Salary: 110000
Employee Name: Amy Salary: 14000

That's all for this topic Java Stream - filter() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - limit() With Examples
  2. Java Stream - distinct() With Examples
  3. Reduction Operations in Java Stream API
  4. Parallel Stream in Java Stream API
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. Pre-defined Functional Interfaces in Java
  2. Effectively Final in Java 8
  3. Heap Memory Allocation in Java
  4. Java Variable Types With Examples
  5. Java Record Class With Examples
  6. Spring Expression Language (SpEL) With Examples
  7. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
  8. Python String isnumeric() Method

No comments:

Post a Comment