Java Stream distinct()方法

Java Stream distinct()方法

distinct() 返回一个由流中不同元素组成的流。 distinct()是 Stream 接口的方法。这个方法使用hashCode()和equals()方法来获取不同的元素。在有序流的情况下,独特元素的选择是稳定的。但是,在无序流的情况下,不同元素的选择不一定是稳定的,可能会发生变化。 distinct()执行 有状态的中间操作 ,即它在内部保持一些状态以完成操作。

语法:

Stream<T> distinct()

下面给出了一些例子,以更好地理解函数的实现。

其中,Stream是一个接口,该函数 返回一个由不同元素组成的流 元素组成。

例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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程