Compare two arrays with not the same order

MrSamuelSmith :

I'm new in coding and I decided to learn java, groovy. I am making a simple exercise. I got a two array and I must compare them if they are equal. I take values from 2 database and these databases are same, but values are not in the same order, but they are equal. For example, I have:

ArrayList collection1 = ["test","a"]
ArrayList collection2 = ["a","test"]

Well I tried this:

assert collection1.equals(collection2)

But I know that this works only when values in those arrays are placed in same order.

Lino :

I can think of two methods:

  1. Check that they are equal sizes
  2. Wrap the two arrays with Arrays.asList()
  3. Check if a contains all elements from b
public static boolean equals(Object[] a, Object[] b) {
    return a.length == b.length && Array.asList(a).containsAll(Arrays.asList(b));
}

Another way would be to just iterate over both arrays at once and then check if the elements are equal:

public static boolean equals(Object[] a, Object[] b) {
    if(a.length != b.length) return false;
    outer: for(Object aObject : a) {
         for(Object bObject : b) {
              if(a.equals(b)) continue outer;
         }
         return false;
    }
    return true;
}

Both methods are rather fast, the first introduces an additional wrapper around the arrays, but is neglectable as Arrays.asList() just uses the given array as a View and does not do any additional copying.


Now it seems that you're actually comparing two Collections, then you can just use this approach:

public static boolean equals(Collection<?> a, Collection<?> b) {
     return a.size() == b.size() && a.containsAll(b);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=144870&siteId=1