流动Java中的distinct()

独特的 返回由流中不同元素组成的流。distinct()是 流动 界面这种方法使用 hashCode() 等于 方法获得不同的元素。在有序流的情况下,不同元素的选择是稳定的。但是,在无序流的情况下,不同元素的选择不一定是稳定的,而且可能会发生变化。distinct()执行 有状态中间操作 i、 它在内部保持某种状态以完成操作。

null

语法:

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
© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享