Home  >  Article  >  Java  >  What is the importance of Collectors.filtering() method in Java 9?

What is the importance of Collectors.filtering() method in Java 9?

WBOY
WBOYforward
2023-08-27 14:17:05911browse

The

Java 9中Collectors.filtering()方法的重要性是什么?

Collectors class is an important part of the StreamAPI. In Java 9, a new method: filtering() was added to the Collectors class. Collectors.filtering()The method can be used to filter elements in the stream. It is similar to the filter() method on a stream. The filter() method processes the values ​​before grouping, while the filtering() method works well with the Collectors.groupingBy() method when filtering Group values ​​before the step occurs.

Syntax

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

Example

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

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

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

      System.out.println(result);
   }
}

Output

<strong>{1=[x], 2=[yy], 3=[www]}</strong>

The above is the detailed content of What is the importance of Collectors.filtering() method in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete