当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。