【发布时间】:2017-02-28 14:14:09
【问题描述】:
这里是一个完整的新手,所以如果我的问题很愚蠢,我深表歉意。老实说,我在发布之前尝试过。 我有一些客户的列表,其中一列是他们的客户 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);
}
}
【问题讨论】:
-
使用
HashMap<Intger, Customer> -
这篇文章对你有用Remove Duplicate
标签: java list collections set hashset