當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java streams counting()用法及代碼示例


在Java 8中,有一個由Collectors類counting()方法返回的預定義counting()方法,以對Stream中的元素數進行計數。

用法:
public static Collector counting() Where, output is a Collector, acting on a Stream of elements of type T, with its finisher returning the ‘collected’ value of type Long. It is a terminal operation which returns the total count of elements in the stream which reach the collect() method after undergoing various pipelined stream operations such as filtering.

範例1:計算整數流中的元素。


// Java code to count number of elements  
// in stream 
import java.util.stream.Stream; 
import java.util.stream.Collectors; 
class counting { 
    public static void main(String[] args) 
    { 
        // creating stream of integers 
        Stream<Integer> i = Stream.of(1, 2, 3, 4, 5, 6); 
  
        // counting number of integer in stream 
        long count_int = i.collect(Collectors.counting()); 
  
        System.out.println(count_int); 
    } 
}
輸出:
6

範例2:計算String流中的元素。

// JAVA code to count number of elements in stream 
import java.util.stream.Stream; 
import java.util.stream.Collectors; 
  
class counting { 
    public static void main(String[] args) 
    { 
        // creating stream of strings 
        Stream<String> s = Stream.of("Akash","Harsh", 
                        "Shubham","Nishant","Pratik"); 
  
        // counting number of strings in stream 
        long count_string =  s.collect(Collectors.counting()); 
  
        System.out.println(count_string); 
    } 
}
輸出:
5


相關用法


注:本文由純淨天空篩選整理自akash1295大神的英文原創作品 Java streams counting() method with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。