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

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

    You could use a stream if the lists are random access lists (so that a call to get is fast - generally constant time) leading to:

    //checks for null and size before
    boolean same = IntStream.range(0, list1.size()).allMatch(i -> Arrays.equals(list1.get(i), list2.get(i)));
    

    However, you might give as parameters some implementations that are not (such as LinkedLists). In this case, the best way is to use the iterator explicitly. Something like:

    boolean compare(List list1, List list2) {
    
        //checks for null and size
    
        Iterator iteList1 = list1.iterator();
        Iterator iteList2 = list2.iterator();
    
        while(iteList1.hasNext()) {
            if(!Arrays.equals(iteList1.next(), iteList2.next())) {
                return false;
            }
        }
        return true;
    }
    

提交回复
热议问题