I have two lists, let's say:
def list1 = ["ABC", "DEF", "GHI", "JKL"]
def list2 = ["ABC", "DEF", "JKL", "GHI"]
I want to compare these two lists and make sure that the values they have are the same, despite the order in which they appear.
I've tried this but it doesn't seem to work:
assert new HashSet( Arrays.asList(list1)).equals(new HashSet( Arrays.asList(list2)))
Could anyone point me in the right direction? Much appreciated.
CodePudding user response:
If you want to stay with List
s and not use Set
s, you can compare sorted lists:
def list1 = ["ABC", "DEF", "GHI", "JKL"]
def list2 = ["ABC", "DEF", "JKL", "GHI"]
assert list1 != list2
assert list1.sort() == list2.sort()
The suggested Set-based comparison might be dangerous, it the lists contain different numbers of duplicates:
def list1 = ["ABC"]
def list2 = ["ABC", "ABC", "ABC"]
assert list1.sort() != list2.sort()
assert list1 as Set == list2 as Set // GOTCHA!
CodePudding user response:
Your comparison is not working because you're comparing sets of lists.
new HashSet(Arrays.asList())
creates a HashSet<List<String>>
(roughly), and when Set equality is being checked, the element-wise comparison calls the usual List.equals
, which doesn't work because order matters in lists.
Your lists should make flat elements in target sets for it to work based on Set comparison logic (such that you compare instances of HashSet<String>
instead of HashSet<List<String>>
). Your code should be
new HashSet(list1).equals(new HashSet(list2))