java中distinct的用法

distinct() 方法去除流中重复元素,返回一个仅包含不重复元素的新流。语法:Stream distinct()。用法:使用自定义比较器可按属性比较元素;流管道可先过滤元素再去除重复。实现基于 HashMap,时间复杂度为 O(n)。

Java 中 distinct() 的用法

distinct() 方法用于从一个流中去除重复元素,返回一个新的流,其中仅包含不重复的元素。

语法:

Stream distinct()

参数:

返回值:

一个新的流,其中仅包含不重复的元素。

使用示例:

List numbers = Arrays.asList(1, 2, 3, 4, 1, 3, 5);

// 使用 distinct() 去除重复元素
List distinctNumbers = numbers.stream()
                                    .distinct()
                                    .toList();

System.out.println(distinctNumbers); // 输出:[1, 2, 3, 4, 5]

注意:

  • distinct() 比较的是对象的引用相等性。如果您需要比较对象的属性,可以使用自定义比较器。
  • distinct() 的实现基于 HashMap,因此时间复杂度为 O(n),其中 n 是流中的元素数量。

进阶用法:

  • 使用自定义比较器比较元素的属性:
Comparator employeeComparator = Comparator.comparing(Employee::getId);

List employees = ...;

List distinctEmployees = employees.stream()
                                         .distinct(employeeComparator)
                                         .toList();
  • 使用流管道过滤元素,然后使用 distinct() 去除重复元素:
List names = ...;

List distinctNames = names.stream()
                                 .filter(name -> name.length() > 5)
                                 .distinct()
                                 .toList();