Is there a way to check if two Collections contain the same elements, independent of order?

后端 未结 3 1430
深忆病人
深忆病人 2020-12-01 09:20

I\'ve been looking for a method that operates like Arrays.equals(a1, a2), but ignoring the element order. I haven\'t been able to find it in either Google Colle

相关标签:
3条回答
  • 2020-12-01 09:42

    If you want to ignore order, then how about testing sets for equality?

    new HashSet(c1).equals(new HashSet(c2))
    
    0 讨论(0)
  • 2020-12-01 09:44

    This is three method calls and uses Google CollectionsGuava, but is possibly as simple as it gets:

    HashMultiset.create(c1).equals(HashMultiset.create(c2));
    

    Creating the temporary Multisets may appear wasteful, but to compare the collections efficiently you need to index them somehow.

    0 讨论(0)
  • 2020-12-01 09:46

    Apache commons-collections has CollectionUtils#isEqualCollection:

    Returns true if the given Collections contain exactly the same elements with exactly the same cardinality.

    That is, if the cardinality of e in a is equal to the cardinality of e in b, for each element e in a or b.

    Which is, I think, exactly what you're after.

    0 讨论(0)
提交回复
热议问题