Importance of the Collectors.filtering() method in Java 9?


Collectors class is an essential part of the Stream API. In Java 9, a new method: filtering() added to the Collectors class. The Collectors.filtering() method can be used for filtering elements in a stream. It is similar to the filter() method on streams. The filter() method processes the values before they have grouped whereas the filtering() method can be used nicely with the Collectors.groupingBy() method to group the values before the filtering step takes place.

Syntax

public static <T, A, R> Collector<T, ?, R> filtering(Predicate<? super T> predicate, Collector<? super T, A, R> downstream)

Example

import java.util.stream.*;
import java.util.*;

public class FilteringMethodTest {
   public static void main(String args[]) {
      List<String> list = List.of("x", "yy", "zz", "www");

      Map<Integer, List<String>> result = list.stream()
                           .collect(Collectors.groupingBy(String::length,
                            Collectors.filtering(s -> !s.contains("z"),
                            Collectors.toList())));

      System.out.println(result);
   }
}

Output

{1=[x], 2=[yy], 3=[www]}

Updated on: 05-Mar-2020

234 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements