How to compare two arrays with identical elements or not in groovy?

How to compare two arrays with identical elements or not?

def a = [1, 3, 2] def b = [2, 1, 3] def c = [2, 4, 3, 1] 

a and b contain the same elements, but a and c are not.

+6
source share
2 answers

You can try to convert them to Sets and then compare them, since equality in Sets is defined as having the same elements regardless of order.

 assert a as Set == b as Set assert a as Set != c as Set 
+13
source

Just 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 

false passed to sort is designed to prevent reordering in place. If it’s normal to reorder the lists, you can remove it and possibly get a little performance.

+8
source

Source: https://habr.com/ru/post/902818/


All Articles