How to compare equality of lists of arrays with modern Java? How to compare equality of lists of arrays with modern Java? arrays arrays

How to compare equality of lists of arrays with modern Java?


The for loop at least can be streamified, leading to:

return (list1.size()==list2.size() &&        IntStream.range(0, list1.size())                 .allMatch(i -> Arrays.equals(list1.get(i), list2.get(i)));


using zip (which originates from lambda b93) function from https://stackoverflow.com/a/23529010/755183, code could look like:

boolean match = a.size() == b.size() &&                 zip(a.stream(), b.stream(), Arrays::deepEquals).                allMatch(equal -> equal)

update

in order to check size of arrays first and then content this could be a solution to consider

final boolean match = a.size() == b.size()                    && zip(a.stream(), b.stream(), (as, bs) -> as.length == bs.length).                      allMatch(equal -> equal)                   && zip(a.stream(), b.stream(), Arrays::deepEquals).                      allMatch(equal -> equal);


1) Solution based on Java 8 streams:

List<List<String>> first = list1.stream().map(Arrays::asList).collect(toList());List<List<String>> second = list2.stream().map(Arrays::asList).collect(toList());return first.equals(second);

2) Much simpler solution (works in Java 5+):

return Arrays.deepEquals(list1.toArray(), list2.toArray());

3) Regarding your new requirement (to check the contained String arrays length first), you could write a generic helper method that does equality check for transformed lists:

<T, U> boolean equal(List<T> list1, List<T> list2, Function<T, U> mapper) {    List<U> first = list1.stream().map(mapper).collect(toList());    List<U> second = list2.stream().map(mapper).collect(toList());    return first.equals(second);}

Then the solution could be:

return equal(list1, list2, s -> s.length)    && equal(list1, list2, Arrays::asList);