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


Java Stream.distinct()用法及代碼示例


distinct()返回由流中不同元素組成的流。 distinct()是Stream接口的方法。此方法使用hashCode()和equals()方法來獲取不同的元素。在有序流的情況下,不同元素的選擇是穩定的。但是,在無序流的情況下,不同元素的選擇不一定是穩定的,並且可以更改。 distinct()執行有狀態的中間操作,即,它在內部維護一些狀態以完成操作。

用法:

Stream<T> distinct()

Where, Stream is an interface and the function
returns a stream consisting of the distinct 
elements.

下麵給出一些示例,以更好地理解該函數的實現。
示例1:


// Implementation of Stream.distinct() 
// to get the distinct elements in the List 
import java.util.*; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
  
        // Creating a list of integers 
        List<Integer> list = Arrays.asList(1, 1, 2, 3, 3, 4, 5, 5); 
  
        System.out.println("The distinct elements are :"); 
  
        // Displaying the distinct elements in the list 
        // using Stream.distinct() method 
        list.stream().distinct().forEach(System.out::println); 
    } 
}

輸出:

The distinct elements are :
1
2
3
4
5

示例2:

// Implementation of Stream.distinct() 
// to get the distinct elements in the List 
import java.util.*; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
  
        // Creating a list of strings 
        List<String> list = Arrays.asList("Geeks", "for", "Geeks", 
                                          "GeeksQuiz", "for", "GeeksforGeeks"); 
  
        System.out.println("The distinct elements are :"); 
  
        // Displaying the distinct elements in the list 
        // using Stream.distinct() method 
        list.stream().distinct().forEach(System.out::println); 
    } 
}

輸出:

The distinct elements are :
Geeks
for
GeeksQuiz
GeeksforGeeks

示例3:

// Implementation of Stream.distinct() 
// to get the count of distinct elements 
// in the List 
import java.util.*; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
  
        // Creating a list of strings 
        List<String> list = Arrays.asList("Geeks", "for", "Geeks", 
                                          "GeeksQuiz", "for", "GeeksforGeeks"); 
  
        // Storing the count of distinct elements 
        // in the list using Stream.distinct() method 
        long Count = list.stream().distinct().count(); 
  
        // Displaying the count of distinct elements 
        System.out.println("The count of distinct elements is : " + Count); 
    } 
}

輸出:

The count of distinct elements is : 4


相關用法


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