How can I compare two arrays contains same items or not?
def a = [1, 3, 2]
def b = [2, 1, 3]
def c = [2, 4, 3, 1]
a & b are contains same items, but a & c not.
You can try converting them into Sets and then comparing them, as the equality in Sets is defined as having the same elements regardless of the order.
assert a as Set == b as Set
assert a as Set != c as Set
Simply sorting the results and comparing is an easy way, if your lists are not too large:
def a = [1, 3, 2]
def b = [2, 1, 3]
def c = [2, 4, 3, 1]
def haveSameContent(a1, a2) {
a1.sort(false) == a2.sort(false)
}
assert haveSameContent(a, b) == true
assert haveSameContent(a, c) == false
The false
passed to sort
is to prevent in-place reordering. If it's OK to change the order of the lists, you can remove it and possibly gain a little bit of performance.
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