Java IntStream distinct()方法及实例

来源:这里教程网 时间:2026-02-17 20:56:15 作者:

Java IntStream distinct()方法及实例

IntStream distinct()java.util.stream.IntStream的一个方法。该方法返回一个由不同元素组成的流。这是一个有状态的中间操作,也就是说,在处理新的元素时,它可能会纳入以前看到的元素的状态。

语法:

IntStream distinct()

其中,IntStream是一连串的
原始的int-value元素的序列。

例子1: 打印整数流的不同元素。

// 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);      }}

输出:

23568

例2: 计算一个流中不同元素的值。

// Java code for IntStream distinct() method// to count the number of distinct // elements in given streamimport 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

相关推荐