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