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

I have ArrayList<SomeObject>in java that contains <SomeObject>several times. I also have Set<SomeObject>that contains only some elements. Elements are unambiguously distinguishable only by their name ( String SomeObject.Name).

How can I see if the list has the same elements as the set, but maybe several times?

thanks

+4
source share
6 answers

There are several collection libraries for this. For example, commons-collection: http://commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/CollectionUtils.html#isEqualCollection(java.util.Collection, % 20java.util.Collection)

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

mySet.containsAll(myList) && myList.containsAll(mySet)
+2
source

You can convert an ArrayList to a set using a HashSet:

HashSet listSet = new HashSet(arrayList);

To check if an element ArrayListinitially has more elements, simply compare the results listSetand ArrayList size():

boolean sameSize = listSet.size() == arrayList.size()

Then you can get the intersection of two sets (common elements):

listSet.retainAll(set1)

listSet.size() == set1.size(), , . , , : if sameSize is true, , false , .

+2

, , ,

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

..., list , set.

+2

:

  • , ;
  • , .
0

All Java collections have a method boolean containsAll(collection<>), so if we want to check if two collections contain the same elements, we can write collection1.containsAll(collection2) && collection2.containsAll(collection1)which will return trueif collection1they collection2contain the same elements.

0
source

Create a hash that is a string and an integer from a count of the amount of time. Interate believes that the list creates a Hash record and sets the value to one if the item already adds one to the account.

Hash<String, Integer> hash = new HashMap<String, Integer>();
for (String s : list) {
    if (hash.containsKey(s))
        hash.put(s, hash.get(s)++);
    else
        hash.put(s,1);
}
0
source

Source: https://habr.com/ru/post/1525331/


All Articles