Java 流的 counting() 方法及示例
在本文中,我們將學習如何使用 Java 流 中的 counting() 方法來計算流中元素的數量。Java 流提供了一種高效處理資料集合的方法,而 Collectors.counting() 方法則是一種簡單有效地計算流中元素數量的方法。
問題陳述
給定一個元素流,實現一個 Java 程式,使用 Collectors.counting() 方法來計算流中元素的數量。輸入
Initial Stream: Stream.of("Kevin", "Jofra", "Tom", "Chris", "Liam")
輸出
Number of elements in the stream: 5
計算流中元素數量的步驟
以下是計算流中元素數量的步驟
- 從 java.util 和 java.util.stream 包匯入必要的類。
- 建立一個元素流(字串或整數)。
- 應用 collect (Collectors.counting()) 方法來計算流中元素的數量。
- 顯示元素計數。
Java 程式:計算流中元素的數量
以下是如何計算流中元素數量的示例
import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<String> stream = Stream.of("Kevin", "Jofra","Tom", "Chris", "Liam"); // count long count = stream.collect(Collectors.counting()); System.out.println("Number of elements in the stream = "+count); } }
輸出
Number of elements in the stream = 5
計算整數流中的元素
輸入
Initial Stream: Stream.of(5, 10, 20, 40, 80, 160)
輸出
Number of elements in the stream: 6
Java 程式:計算流中整數元素的數量
以下是另一個計算 流中整數元素數量的示例
import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<Integer> stream = Stream.of(5, 10, 20, 40, 80, 160); // count long count = stream.collect(Collectors.counting()); System.out.println("Number of elements in the stream = "+count); } }
輸出
Number of elements in the stream = 6
程式碼解釋
在這兩個示例中,我們都建立了一個元素流,可以是字串或整數。我們在 collect() 函式中使用 Collectors.counting() 方法來計算流中的元素。此方法將流中元素的總數作為長整型值返回。結果使用 System.out.println() 列印,顯示各個流中元素的數量。廣告