Java 8 中的 Collectors counting() 方法


Java 8 Collectors 類的 counting() 方法返回一個接受型別為 T 的收集器,該收集器可計算輸入元素的數量。

語法如下 −

static <T> Collector<T,?,Long> counting()

在此,引數 −

  • T − 輸入元素的型別

  • Long − 此類的原始型別 long 值,表示一個物件

要在 Java 中使用 Collectors 類,需要匯入以下包 −

import java.util.stream.Collectors;

以下是 Java 8 中實現 counting() 方法的示例 −

示例

 線上演示

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("25", "50", "75", "100", "125", "150", "200");
      long res = stream.collect(Collectors.counting());
      System.out.println("Count of elements in the stream = "+res);
   }
}

輸出

Count of elements in the stream = 7

更新於: 30-7-2019

1K+ 瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.