Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two lists with no duplicates

Tags:

java

list

set

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);
like image 959
edwardmlyte Avatar asked May 23 '11 14:05

edwardmlyte


1 Answers

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.

like image 93
Kaj Avatar answered Oct 01 '22 13:10

Kaj