gpt4 book ai didi

java - 从 java 集合中删除重复项

转载 作者:行者123 更新时间:2023-12-01 06:49:07 25 4
gpt4 key购买 nike

public class Employee implements Comparable<Employee> {

private int id;
private String name;
private String salary;
private String recordStatus;
private int key;

public Employee(int id, String name, String salary, int key) {
super();
this.id = id;
this.name = name;
this.salary = salary;
this.key = key;
}
}

现在我有一个 Employee 类型的列表。

List<Employee> list = new ArrayList<Employee>();
list.add(new Employee(123, "zMadhu", "1000$",1));
list.add(new Employee(332, "bSudhan", "2000$",2));
list.add(new Employee(54, "cKongarass", "3000$",3));
list.add(new Employee(54, "xKongarass", "3000$",4));
list.add(new Employee(54, "aKongarass", "3000$",5));

现在我想从此列表中删除数据并只拥有唯一的 IDS。 IE。我预计另一个 Employee 类型列表中有 54,123,332 个。

想看看我该怎么做。非常感谢您的帮助。

最佳答案

第一次覆盖equals(..)hashCode()您只使用 id 的地方:

...

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee)) return false;

Employee employee = (Employee) o;

return id == employee.id;
}

@Override
public int hashCode() {
return id;
}
...

第二只需创建一个 Set<Employee> 它不会接受重复的对象,如下所示:

Set<Employee> result = new HashSet<>(list);// [54, 123, 332]
<小时/>

看一个简单的Ideone demo

关于java - 从 java 集合中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52296449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com