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

后端 未结 5 1585
清酒与你
清酒与你 2021-01-31 07:18

I have two lists of arrays.

How do I easily compare equality of these with Java 8 and its features, without using external libraries? I am looking for a \"bett

5条回答
  •  余生分开走
    2021-01-31 07:32

    1) Solution based on Java 8 streams:

    List> first = list1.stream().map(Arrays::asList).collect(toList());
    List> 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:

     boolean equal(List list1, List list2, Function mapper) {
        List first = list1.stream().map(mapper).collect(toList());
        List 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);
    

提交回复
热议问题