📜  Java中的 Stream.distinct()

📅  最后修改于: 2022-05-13 01:55:03.446000             🧑  作者: Mango

Java中的 Stream.distinct()

distinct()返回由流中不同元素组成的流。 distinct() 是Stream接口的方法。此方法使用hashCode()equals()方法来获取不同的元素。在有序流的情况下,不同元素的选择是稳定的。但是,在无序流的情况下,不同元素的选择不一定是稳定的并且可以改变。 distinct() 执行有状态的中间操作,即它在内部维护一些状态以完成操作。

句法 :

Stream 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 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 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 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