java的stream中.distinct函数
时间: 2025-06-29 14:06:18 浏览: 9
### Java Stream API 中 `distinct` 方法使用教程
#### 1. `distinct` 方法概述
`distinct()` 是 Java 8 Stream API 提供的一个中间操作,用于去除流中的重复元素并返回一个新的流。此方法依赖于对象的 `hashCode()` 和 `equals()` 方法来识别相同的元素[^1]。
#### 2. 基本数值类型去重示例
对于基本数据类型的列表,可以直接调用 `distinct()` 来移除重复项:
```java
final List<Integer> numbers = Arrays.asList(1, 1, 2, 2, 3, 4, 5);
List<Integer> uniqueNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(uniqueNumbers); // 输出: [1, 2, 3, 4, 5]
```
上述代码创建了一个整数列表,并通过 `stream()` 转换成流形式;接着应用 `.distinct()` 移除了所有重复值;最后再收集结果到新的列表中打印出来[^2]。
#### 3. 自定义对象类型去重
当处理的是自定义类的对象时,为了使 `distinct()` 正常工作,需要确保这些类已经正确实现了 `hashCode()` 和 `equals()` 方法。下面是一个简单的例子展示如何去重员工记录:
假设有一个名为 Employee 的类,其中包含 id 和 name 属性:
```java
class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee)) return false;
Employee employee = (Employee) o;
return getId() == employee.getId();
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
// Getters and setters...
}
```
现在可以安全地对 Employees 列表执行 distinct 操作而不用担心相同 ID 的条目被错误地标记为不同实体:
```java
List<Employee> employees = Arrays.asList(
new Employee(1,"Alice"),
new Employee(2,"Bob"),
new Employee(1,"Charlie") // Duplicate by ID with Alice
);
List<Employee> uniqueEmployees = employees.stream()
.distinct()
.collect(Collectors.toList());
uniqueEmployees.forEach(e -> System.out.println(e.getName()));
// 只会输出 "Alice", "Bob"
```
这段程序展示了如何基于特定字段(这里是ID)来进行有效的去重操作[^4]。
阅读全文
相关推荐



















