开发者

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


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.


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)


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


// 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;
}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜