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


Collectors 類是Stream API的重要組成部分。在 Java 9 中,向Collectors 類添加了一個新方法:filtering()Collectors.filtering() 方法可用於過濾流中的元素。它類似於流上的filter()方法。filter()方法在對值進行分組之前對其進行處理,而filtering()方法可以在過濾步驟發生之前與Collectors.groupingBy() 方法很好地結合使用,以對值進行分組。

語法

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

示例

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);
   }
}

輸出

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

更新時間:2020 年 3 月 5 日

306 次瀏覽

開啟 職業生涯

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.