LinkedHashSet remove duplicates object(LinkedHashSet 删除重复对象)
问题描述
I have simple question to you, I have class Product that have fields like this:
private Integer id;
private String category;
private String symbol;
private String desc;
private Double price;
private Integer quantity;
I want to remove duplicates item from LinkedHasSet based on ID, e.g Products that have same ID but diffrent quantity will be add to set, I want to remove (update) products with same ID, and it will by my unique id of object, how to do that?
e.g Product: id=1, category=CCTV, symbol=TVC-DS, desc=Simple Camera, price=100.00, quantity=1 Product: id=1, category=CCTV, symbol=TVC-DS, desc=Simple Camera, price=100.00, quantity=3
won't be added to set
my code:
public void setList(Set<Product> list) {
if(list.isEmpty())
this.list = list;
else {
this.list.addAll(list);
Iterator<Product> it = this.list.iterator();
for(Product p : list) {
while(it.hasNext()) {
if(it.next().getId() != p.getId())
it.remove();
this.list.add(p);
}
}
}
}
All Set
implementations remove duplicates, and the LinkedHashSet
is no exception.
The definition of duplicate is two objects that are equal to each other, according to their equals()
method. If you haven't overridden equals
on your Product
class, then only identical references will be considered equal - not different instances with the same values.
So you need to add a more specific implementation of equals
(and hashcode
) for your class. For some examples and guidance, see Overriding equals and hashcode in Java. (Note that you must override hashcode
as well, otherwise your class will not behave correctly in hash sets.)
这篇关于LinkedHashSet 删除重复对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:LinkedHashSet 删除重复对象
基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01