java怎么实现对一个List中的实体的名字和部门进行去重
时间: 2024-03-11 18:51:19 浏览: 17
要对List中的实体的名字和部门进行去重,可以通过实现实体类的equals()和hashCode()方法来实现。代码示例如下:
```java
public class Employee {
private String name;
private String department;
// 省略构造方法和getter/setter方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee)) return false;
Employee employee = (Employee) o;
return Objects.equals(name, employee.name) &&
Objects.equals(department, employee.department);
}
@Override
public int hashCode() {
return Objects.hash(name, department);
}
}
```
然后遍历List,将每个元素加入一个Set中,由于Set的特性,重复的元素将被自动去重。代码示例如下:
```java
List<Employee> employeeList = new ArrayList<>();
// 添加元素到employeeList中
Set<Employee> employeeSet = new HashSet<>(employeeList);
// employeeSet即为去重后的结果
```
这样就可以对List中的实体的名字和部门进行去重了。