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


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

LongStream distinct()是java.util.stream.LongStream中的方法。此方法返回由不同元素組成的流。這是有狀態的中間操作,即,在處理新元素時,它可以合並先前看到的元素的狀態。

用法:

LongStream distinct()

Where, LongStream is a sequence of 
primitive long-valued elements.

下麵給出一些示例,以更好地理解該函數。
示例1:打印長流的不同元素。


// Java code for LongStream distinct() 
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, 
                              3L, 5L, 6L, 6L, 8L); 
  
        // Displaying only distinct elements 
        // using the distinct() method 
        stream.distinct().forEach(System.out::println); 
    } 
}
輸出:
2
3
5
6
8

示例2:計算流中不同元素的值。

// Java code for LongStream distinct() method 
// 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, 3L, 
                                      5L, 6L, 6L, 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 distinct() in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。