Java 中的 Stream.distinct ()方法使用
流类的distinct()方法返回由该流的不同元素组成的流。语法如下-
Stream<T> distinct()
示例
以下是在Stream类中实现distinct()方法的示例-
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 30, 40, 40, 50, 70, 90, 90, 100);
System.out.println("List = "+list);
System.out.println("Displaying only the distinct elements = ");
list.stream().distinct().forEach(System.out::println);
}
}输出结果
List = [10, 30, 40, 40, 50, 70, 90, 90, 100] Displaying only the distinct elements = 10 30 40 50 70 90 100
示例
让我们看另一个例子-
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 30, 40, 40, 50, 70, 90, 90, 100);
System.out.println("List = "+list);
System.out.println("Count of distinct elements = "+(list.stream().distinct().count()));
System.out.println("Displaying only the distinct elements = ");
list.stream().distinct().forEach(System.out::println);
}
}输出结果
List = [10, 30, 40, 40, 50, 70, 90, 90, 100] Count of distinct elements = 7 Displaying only the distinct elements = 10 30 40 50 70 90 100
热门推荐
10 教练生日祝福语 简短独特
11 送去考试祝福语大全简短
12 家长祝福语大全简短内容
13 女朋友祝福语简短新年
14 夸赞老师祝福语搞笑简短
15 男士送花祝福语大全简短
16 简短霸气的考试祝福语
17 考试祝福语日文简短版
18 简短祝福语大全暖心