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


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

DoubleStream distinct()是java.util.stream.DoubleStream中的方法。此方法返回由不同元素組成的流。這是有狀態的中間操作,即,在處理新元素時,它可以合並先前看到的元素的狀態。他們可能需要在產生結果之前處理整個輸入。例如,在查看流的所有元素之前,不能對流進行排序而產生任何結果。

用法:

DoubleStream distinct()

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

示例1:打印Double流的不同元素。


// Java code for DoubleStream distinct() 
import java.util.*; 
import java.util.stream.DoubleStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // creating a stream 
        DoubleStream stream = DoubleStream.of(2.2, 3.3, 3.3, 
                                        5.6, 6.7, 6.7, 8.0); 
  
        // Displaying only distinct elements 
        // using the distinct() method 
        stream.distinct().forEach(System.out::println); 
    } 
}

輸出:

2.2
3.3
5.6
6.7
8.0

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

// Java code for DoubleStream distinct() method 
// to count the number of distinct 
// elements in given stream 
import java.util.*; 
import java.util.stream.DoubleStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
  
        // creating a stream 
        DoubleStream stream = DoubleStream.of(2.2, 3.3, 3.3, 
                                         5.6, 6.7, 6.7, 8.0); 
  
        // 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大神的英文原創作品 DoubleStream distinct() in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。