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

后端 未结 5 1630
清酒与你
清酒与你 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:36

    You could stream over one list and compare to each element of the other by using an iterator:

    Iterator it = list1.iterator();
    boolean match = list1.size() == list2.size() &&
                    list2.stream().allMatch(a -> Arrays.equals(a, it.next()));
    

    Using an iterator instead of the get(index) method on the first list is better because it doesn't matter whether the list is RandomAccess or not.

    Note: this only works with a sequential stream. Using a parallel stream will lead to wrong results.


    EDIT: As per the question last edit, which indicates it would be better to check the length of every pair of arrays in advance, I think it could be achieved with a slight modification to my previous code:

    Iterator itLength = list1.iterator();
    Iterator itContents = list1.iterator();
    
    boolean match = 
            list1.size() == list2.size()
        && 
            list2.stream()
                .allMatch(a -> {
                    String[] s = itLength.next();
                    return s == null ? a == null :
                           a == null ? s == null :
                           a.length == s.length;
                })
        && 
            list2.stream()
                .allMatch(a -> Arrays.equals(a, itContents.next()));
    

    Here I'm using two iterators and am streaming list2 twice, but I see no other way to check all lengths before checking the contents of the first pair of arrays. Check for lengths is null-safe, while check for contents is delegated to the Arrays.equals(array1, array2) method.

提交回复
热议问题