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

15,305

Solution 1

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

Solution 2

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.

Share:
15,305
nikli
Author by

nikli

Writing Desktop, Web and RESTful applications Create documentation for new and existing applications Create pipelines for CI Write Unit Tests

Updated on June 16, 2022

Comments

  • nikli
    nikli almost 2 years

    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.

  • epidemian
    epidemian over 12 years
    There is no point in comparing a boolean value with true or false. I think assert haveSameContent(a, b) and assert !haveSameContent(a, c) reads better.
  • OverZealous
    OverZealous over 12 years
    That's really a matter of opinion. I think it makes it clearer with the == false that you expect a false output. It's rather easy to miss a single exclamation mark when skimming code. (Also, don't forget, due to Groovy truth, !0 or ![] returns true, but assert [] == false will fail.)
  • Ted Naleid
    Ted Naleid over 12 years
    That works as long as the list elements are not duplicated. For lists that can have duplicates, this method won't detect if they have the same number of each individual element. (I don't get the impression this is something the OP cares about so your answer is still valid, just an FYI for others that find this answer).