LongStream distinct()是java.util.stream.LongStream中的方法。此方法返回由不同元素组成的流。这是有状态的中间操作,即,在处理新元素时,它可以合并先前看到的元素的状态。
用法:
LongStream distinct()
Where, LongStream is a sequence of
primitive long-valued elements.
下面给出一些示例,以更好地理解该功能。
示例1:打印长流的不同元素。
// Java code for LongStream distinct()
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// creating a stream
LongStream stream = LongStream.of(2L, 3L,
3L, 5L, 6L, 6L, 8L);
// Displaying only distinct elements
// using the distinct() method
stream.distinct().forEach(System.out::println);
}
}
输出:
2
3
5
6
8
示例2:计算流中不同元素的值。
// Java code for LongStream distinct() method
// to count the number of distinct
// elements in given stream
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// creating a stream
LongStream stream = LongStream.of(2L, 3L, 3L,
5L, 6L, 6L, 8L);
// storing the count of distinct elements
// in a variable named total
long total = stream.distinct().count();
// displaying the total number of elements
System.out.println(total);
}
}
输出:
5