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


Java LongStream count()用法及代碼示例


長流count()返回流中元素的數量。 LongStream count()存在於java.util.stream.LongStream中
用法:

long count()

示例1:計算LongStream中的元素。

// Java code for LongStream count() 
// to count the number of elements in 
// given stream 
import java.util.*; 
import java.util.stream.LongStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // creating a stream 
        LongStream stream = LongStream.of(2L, 3L, 4L, 5L, 
                                          6L, 7L, 8L); 
  
        // storing the count of elements 
        // in a variable named total 
        long total = stream.count(); 
  
        // displaying the total number of elements 
        System.out.println(total); 
    } 
}
輸出:
7

示例2:計算給定範圍內的元素。

// Java code for LongStream count() 
// to count the number of elements in 
// given range excluding the last element 
import java.util.*; 
import java.util.stream.LongStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // creating a stream 
        LongStream stream = LongStream.range(2, 50); 
  
        // storing the count of elements 
        // in a variable named total 
        long total = stream.count(); 
  
        // displaying the total number of elements 
        System.out.println(total); 
    } 
}
輸出:
48

示例3:計算LongStream中的不同元素。

// Java code for LongStream count() 
// to count the number of distinct 
// elements in given stream 
import java.util.*; 
import java.util.stream.LongStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // creating a stream 
        LongStream stream = LongStream.of(2L, 3L, 4L, 4L, 
                                          7L, 7L, 8L); 
  
        // storing the count of distinct elements 
        // in a variable named total 
        long total = stream.distinct().count(); 
  
        // displaying the total number of elements 
        System.out.println(total); 
    } 
}
輸出:
5


相關用法


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