Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare two arrays contains same items or not in groovy?

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.

like image 946
nikli Avatar asked Dec 01 '11 06:12

nikli


2 Answers

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
like image 115
epidemian Avatar answered Oct 06 '22 23:10

epidemian


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.

like image 38
OverZealous Avatar answered Oct 06 '22 23:10

OverZealous