I want to add the items from a list to another list without any duplicates. I've used the method below involving a set. Is this the most efficient way to achieve the end result? Is there a neater way of updating lista to contain the unique setboth objects?
Set setboth = new HashSet(lista);
setboth.addAll(listb);
lista.clear();
lista.addAll(setboth);
Looks ok, but it depends on if the items implements equals and hashCode.
The HashSet data structure relies on valid implementations of equals, and hashCode. Classes that have a toString() implementation that displays the same string for two instances will not be considered as the same instance unless both instances also returns the same hash code, and returns true on equals.
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