Java 中 IntStream filter() 方法


Java 中 IntStream 類的 filter() 方法返回一個流,其中包含與給定謂詞匹配的此流的元素。

語法如下 -

IntStream filter(IntPredicate predicate)

這裡,謂詞引數是一個無狀態謂詞,應用於每個元素以確定是否應包括該元素。上方的 IntPredicate 是一個 int 值引數的謂詞。

建立一個 IntStream 並新增元素 -

IntStream intStream = IntStream.of(20, 34, 45, 67, 89, 100);

現在,設定一個條件並使用 filter() 方法根據該條件過濾流元素 -

intStream.filter(a -> a < 50).

以下示例演示了在 Java 中實現 IntStream filter() 方法 -

示例

 線上演示

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

public class Demo {
   public static void main(String[] args) {
      IntStream intStream = IntStream.of(20, 34, 45, 67, 89, 100);
      System.out.println("The following elements matches the given predicate:");
      intStream.filter(a -> a < 50).forEach(System.out::println);
   }
}

輸出

The following elements matches the given predicate:
20
34
45

更新於: 2019 年 7 月 30 日

469 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.