September 6, 2021

Java Stream filter() With Examples

In the Java Stream API tutorial we have gone through the intermediate and terminal operations, in this tutorial we’ll go through Java Stream filter() method in detail.

Java Stream filter method

filter() is an intermediate operation which returns a stream consisting of the elements of this stream that match the given condition.

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

Condition passed as argument to the filter method is an implementation of the Predicate which is a functional interface where you implement a boolean valued function.

Java Stream filter method examples

1. In this simple example we have a List of numbers and using filter method we get a new Stream of only those numbers which are greater than 5.

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

public class FilterDemo {
  public static void main(String[] args) {
    // List of numbers
    List<Integer> myList = Arrays.asList(17, 4, 23, 34, 1, 5, 8, 10);  
    Stream<Integer> myStream = myList.stream().filter(n -> n > 5);
    myStream.forEach(System.out::println);
  }
}
Output
17
23
34
8
10

2. Filtering and collecting to a List. You can also convert the returned stream from the filter() method to a list by using Collectors.toList() method.

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

public class FilterDemo {
  public static void main(String[] args) {
    // List of numbers
    List<Integer> myList = Arrays.asList(17, 4, 23, 34, 1, 5, 8, 10);  
    // List with resulting elements
    List<Integer> newList = myList.stream().filter(n -> n > 5).collect(Collectors.toList());
    newList.forEach(System.out::println);
  }
}

3. Java Stream filter example with multiple conditions. You can also combine several conditions by using conditional operators and(&&), or(||). For example from the list of numbers if you want only those numbers which are greater than 5 and also even.

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

public class FilterDemo {
  public static void main(String[] args) {
    // List of numbers
    List<Integer> myList = Arrays.asList(17, 4, 23, 34, 1, 5, 8, 10);  
    // List with resulting elements
    List<Integer> newList = myList.stream().filter(n -> n > 5 && n % 2 == 0).collect(Collectors.toList());
    newList.forEach(System.out::println);
  }
}
Output
34
8
10

Predicate interface also provide methods to compose more than one Predicate. There are the following methods in Predicate which can also be used.

and(Predicate<? super T> other), or(Predicate<? super T> other), not(Predicate<? super T> target)

Here is the example shown above written using Predicate.and() method.

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

public class FilterDemo {
  public static void main(String[] args) {
    // List of numbers
    List<Integer> myList = Arrays.asList(17, 4, 23, 34, 1, 5, 8, 10); 
    Predicate<Integer> p1 = n -> n > 5;
    Predicate<Integer> p2 = n -> n % 2 == 0;
    // List with resulting elements
    List<Integer> newList = myList.stream().filter(p1.and(p2)).collect(Collectors.toList());
    newList.forEach(System.out::println);
  }
}

4. Here is another example of using multiple conditions with filter method. For the example we’ll use the objects of the Student class.

public class Student {
  private int rollNo;
  private String name;
  private String stream;
  private int marks;
  Student(int rollNo, String name, String stream, int marks){
    this.rollNo = rollNo;
    this.name = name;
    this.stream = stream;
    this.marks = marks;
  }
  public int getRollNo() {
    return rollNo;
  }
  public void setRollNo(int rollNo) {
    this.rollNo = rollNo;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getStream() {
    return stream;
  }
  public void setStream(String stream) {
    this.stream = stream;
  }
  public int getMarks() {
    return marks;
  }
  public void setMarks(int marks) {
    this.marks = marks;
  }
  @Override
  public String toString() {
    return "Roll Number: " +  getRollNo() + " Name: " + getName();
  }
}

If you want to get the list of Students that belong to Science stream or Commerce stream that can be done by joining conditions using or.

public class FilterDemo {
  public static void main(String[] args) {
      List<Student> studentList = Arrays.asList(new Student(1, "Peter", "Science", 75),
              new Student(2, "Ram", "Science", 99),
              new Student(3, "Priscilla", "Art", 68),
              new Student(4, "Mahesh", "Art", 62),
              new Student(5, "Scott", "Commerce", 72));
    // List with resulting elements
    List<Student> newList = studentList.stream().filter(s -> s.getStream().equals("Science") || s.getStream().equals("Commerce"))
                          .collect(Collectors.toList());
    newList.forEach(System.out::println);
  }
}
Output
Roll Number: 1 Name: Peter
Roll Number: 2 Name: Ram
Roll Number: 5 Name: Scott

If you want to use Predicate.or() method then the same example can be written as given below.

public class FilterDemo {
  public static void main(String[] args) {
      List<Student> studentList = Arrays.asList(new Student(1, "Peter", "Science", 75),
              new Student(2, "Ram", "Science", 99),
              new Student(3, "Priscilla", "Art", 68),
              new Student(4, "Mahesh", "Art", 62),
              new Student(5, "Scott", "Commerce", 72));
    Predicate<Student> p1 = s -> s.getStream().equals("Science");
    Predicate<Student> p2 = s -> s.getStream().equals("Commerce");
    // List with resulting elements
    List<Student> newList = studentList.stream().filter(p1.or(p2)).collect(Collectors.toList());
    newList.forEach(System.out::println);
  }
}

That's all for the topic Java Stream filter() With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment