LinkedHashSet删除重复的对象 [英] LinkedHashSet remove duplicates object

查看:217
本文介绍了LinkedHashSet删除重复的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题给你,我有类Product有这样的字段:

  private Integer id; 
private String category;
private String symbol;
private String desc;
private double price;
private整数数量;

我想根据ID从LinkedHasSet中删除重复项,例如具有相同ID但不同数量的产品将添加到集合,我想删除(更新)具有相同ID的产品,并且它将通过我的唯一id对象,如何做?



例如
产品:id = 1,category = CCTV,symbol = TVC-DS,desc = Simple Camera,price = 100.00, quantity = 1
产品:id = 1,category = CCTV,symbol = TVC-DS,desc = Simple Camera,price = 100.00, quantity = 3



/ p>

我的代码:

  public void setList(Set< Product> list ){
if(list.isEmpty())
this.list = list;
else {
this.list.addAll(list);
迭代器<产品> it = this.list.iterator();
for(Product p:list){
while(it.hasNext()){
if(it.next()。getId()!= p.getId())
it.remove();
this.list.add(p);
}
}
}
}


解决方案

设置实现删除重复项, LinkedHashSet p>

根据它们的 equals()方法,duplicate的定义是两个彼此相等的对象。如果您没有在 Product 类上重写 equals ,那么只有相同的引用才会被视为相等 - 而不是不同的实例



所以你需要添加一个更具体的实现 equals (和 hashcode )。有关示例和指南,请参见在Java中覆盖equals和hashcode 。 (请注意,您必须重写 hashcode ,否则您的类在哈希集中将无法正确运行。)


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删除重复的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆