edwardmlyte
edwardmlyte

Reputation: 16577

Combine two lists with no duplicates

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

Upvotes: 9

Views: 25941

Answers (5)

Ankit
Ankit

Reputation: 1250

I know this question has been answered, but I think there is another way of doing it and it may be helpful for someone landing on this page.

lista.add(listb);
listb.clear();
listb.add(new ArrayList<String>(new LinkedHashSet<String>(lista)));

Upvotes: 1

Ram Pasupula
Ram Pasupula

Reputation: 5

// CollectionUtils.intersection(ownerList, bcList) returns a collection contains in both ownerList, bcList

CollectionUtils.union unions the listof bc into a unique list

private List getAuthorisedBCList(List bcList, Set> bcOwnersList) { List listList= new ArrayList();

    for(List<String> ownerList : bcOwnersList){
        listList = (List<String>) CollectionUtils.union(listList,CollectionUtils.intersection(ownerList, bcList));
    }
    return listList;
}

Upvotes: 1

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298838

Or you can do this:

list1.removeAll(list2);
list2.addAll(list1);

But it will probably be slower than using a HashSet, depending on the List implementation class. Also, it changes one of the original Lists (which may or may not be an option in your context)

Upvotes: 9

Robin Green
Robin Green

Reputation: 33033

If the final result can just be any Collection, you can just use setBoth directly, without needing to copy all the results into lista.

Upvotes: 2

Kaj
Kaj

Reputation: 10949

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.

Upvotes: 9

Related Questions