这里是一个完全的新手,所以如果我的问题很愚蠢,我深表歉意。老实说,我在发帖之前就尝试过。 我有一些客户的列表,其中一列是他们的客户 ID,另一列是客户名称,第三列是年龄。
我想遍历这个列表并确定相同的 customerId 是否在列表中多次出现。在这种情况下,我需要删除整个客户(即使他的名字或年龄不同)。
您能否建议使用什么来执行此逻辑?
我尝试将客户添加到集合中(因为集合不会添加重复项),但如何声明在此列表中不能重复的是 customerId,而不是客户?
到目前为止,我得到了下面的内容,但按照我的逻辑,没有任何内容表明当客户的 customerId 重复时,该客户被视为重复。 (我不一定需要使用列表。客户是一个对象)。
//Customer is a class that contains a private variable customerId, so I can do customer.getCustomerId();
List<Customer> notDuplicatedCustomers = new ArrayList<Customer>(); //list of customers
final Set<Customer> setToReturn = new HashSet<Customer>();
final Set<Customer> initialSet = new HashSet<Customer>();
for (Customer customer: notDuplicatedCustomers ) {
if (!initialSet.add(customer)) {
setToReturn.add(customer);
}
}
最佳答案
I tried adding the customers to a set (because set would not add duplicates), but how do I state that it is the customerId, not the customer, that cannot be duplicated in this list?
如果您根据 ID 字段覆盖 equals()
方法,从而告诉集合,如果两个客户具有相同的 ID,则它们在逻辑上相等,这是可能的。下面是我的 IDE 生成的示例实现(假设 id 的类型为 String
;如果该类型是某种原始类型,则使用其包装器):
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Student other = (Student) obj;
if (id == null) {
if (other.id!= null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((id == null) ? 0 : id.hashCode());
return result;
}
final Set<Customer> myCustomerSet = new HashSet<Customer>();
myCustomerSet.add(customer1);
...
然后,当您将客户添加到集合中时,集合中应该只有一个具有相同 ID 的条目。
hashCode()
对于您的情况来说不是必需的,但通常如果您重写 equals()
,您还应该重写 hashCode()
。
关于java - 识别客户列表中重复的客户 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40122910/