Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedHashSet remove duplicates object

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);   
            }
        }
    }
}
like image 439
insict Avatar asked Feb 07 '13 09:02

insict


People also ask

Does LinkedHashSet contain duplicates?

Duplicate values are not allowed in LinkedHashSet.

How do you remove duplicate objects?

To remove the duplicates from an array of objects: Create an empty array that will store the unique object IDs. Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.

How HashSet eliminate duplicate user defined objects?

The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList: List<String> al = new ArrayList<>(); // add elements to al, including duplicates Set<String> hs = new HashSet<>(); hs.


1 Answers

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.)

like image 167
Andrzej Doyle Avatar answered Sep 25 '22 16:09

Andrzej Doyle