Java Stream API Filter


A stream made up of the items of this stream that meet the specified predicate is returned by the stream filter function. It is a middle level operation. These actions are always lazy, I.e., running a filter function or other intermediary operations doesn’t really filter anything; instead, it generates a new stream that, when traversed, includes the items of the initial stream that satisfy the provided predicate.

Syntax

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

When T is the type of input of predicate and stream is an interface.

Return type

A new stream.

Implementation

  • Eliminating items that may be divided into a range of numbers from 0 to 10.

  • Removing entries that begin with an uppercase letter at a certain index.

  • Removing components that terminate in a specific alphabetical letter.

Example 1: filter() method with the operation of filtering the elements which are divisible by 5

// Java Program to get a Stream Consisting of the Elements

import java.util.*;
public class Example {
   public static void main(String[] args){
      List<Integer> list = Arrays.asList(3, 4, 6, 12, 20);
      list.stream()
         .filter(num -> num % 5 == 0)
         .forEach(System.out::println);
   }
}

Output

20

Example 2: filter() method with the operation of filtering the elements with an uppercase letter at index 1

// Java Program to Get Stream Consisting of Elements

import java.util.stream.Stream;
public class Example  {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("class", "FOR", "QUIZ", "waytoclass");
      stream.filter(str -> Character.isUpperCase(str.charAt(1)))
         .forEach(System.out::println);
   }
}

Output

FOR
QUIZ

Example 3: filter() method with the operation of filtering the element ending with customs alphabetically letter

// Java Program to Get a Stream Consisting of Elements
import java.util.stream.Stream;
public class Example {

   public static void main(String[] args){
      Stream<String> stream = Stream.of("Class", "FOR", "Quiz", "WaytoClass");
      stream.filter(str -> str.endsWith("s"))
      .forEach(System.out::println);
   }
}

Output

Class
WaytoClass

Conclusion

One approach to improving the functionality of our Java Code is to utilize the filter()method. As opposed to mandatory or methodical. However, there are things to keep in mind while using the filter() function.

For instance, chaining several filter methods carries the danger of making your code run slowly. This is so that a new stream containing the elements that satisfy a predicate’s condition may be created as an intermediary operation. Thus, the key to reducing the amount of filter() calls you make is to merge predicates into a single sentence.

Updated on: 01-Aug-2023

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements