Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Avoid Duplicate in Set<Object>

Tags:

java

set

I have one Set:

final Set<Object> partialResults = new LinkedHashSet<Object>();

Setting values like this:

partialResults.add(createResultList(data.getProduct(), data.getMaterialId()));

private List<Object> createResultList(final ProductModel product, final String code)
    {
        final List<Object> result = new ArrayList<Object>();
        result.add(product);
        result.add(code);
        return result;
    }

It is adding duplicate products; how to avoid adding duplicate records?

like image 423
shitanshu Avatar asked May 30 '26 06:05

shitanshu


2 Answers

Your Set contains ArrayList instances, each containing a ProductModel instance and a String instance. In order for two elements to be considered equal by the LinkedHashSet, they must have the same hashCode and the equals method should return true when applied to both of them.

For ArrayList, hashCode and equals depend on hashCode and equals of the elements of the ArrayList. String overrides hashCode and equals properly, which means you probably didn't override hashCode and equals of ProductModel properly.

like image 134
Eran Avatar answered May 31 '26 19:05

Eran


Either do what Eran suggests or (looking at the use case at hand) change your logic to using a HashMap rather than a Set using the code String as key and the ProductModel object as value. That way you get a unique collection of ProductModels with map.values() and save yourself the hassle of overwriting hashCode and equals in ProductModel.

like image 22
Fritz Duchardt Avatar answered May 31 '26 18:05

Fritz Duchardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!