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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With