Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a set has the same elements as a list in Java?

Tags:

java

list

set

I have an ArrayList<SomeObject> in java which contains some <SomeObject> multiple times. I also have a Set<SomeObject>, which contains some elements one time only. The elements are only uniquely distinguishable only by their name (String SomeObject.Name).

How am I possible to see if the list has exactly the same elements as the set, but maybe multiple times?

Thanks

like image 709
Jim Blum Avatar asked Dec 25 '22 14:12

Jim Blum


2 Answers

There are several collections libraries to do this. For example commons-collection: https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html#isEqualCollection-java.util.Collection-java.util.Collection-

eg. CollectionUtils.isEqualCollection(myList, mySet)

If you have to write it yourself, no libraries, then just check that each contains all the elements of the other:

`mySet.containsAll(myList) && myList.containsAll(mySet)`
like image 63
neildo Avatar answered Jan 03 '23 10:01

neildo


It seems like the simplest one-line solution to this is probably

return new HashSet<SomeObject>(list).equals(set);

...which just identifies the unique elements of list and verifies that that matches set exactly.

like image 24
Louis Wasserman Avatar answered Jan 03 '23 09:01

Louis Wasserman