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
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)`
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.
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