Java Dailly Tip: How to compare two array lists in Java

Java Dailly Tip: How to compare two array lists in Java

Problem

What's the fastest and best way to check if two lists contain the same items? I mean the standard Java library. The order of the elements should not matter, nor their type.

List list1
List list2; 
// ... construct etc

list1.add("A");
list2.add("A"); 
// the function, given these two lists, should return true

Solution

If the lists have the same order then I suggest doing list1.equals (list2). In any other case, for example, you should cast the list onto the Set collection and thus make a comparison. Here is an example:

public static  boolean listEqualsIgnoreOrder(List list1, List list2) {
    return new HashSet<>(list1).equals(new HashSet<>(list2));
}

However, if we want to write the algorithm ourselves, it is also not difficult to implement:

public boolean isDifferentLists(List listOne, List listTwo) {
    if(isNullLists(listOne, listTwo)) {
        return false;
    }

    if (hasDifferentSize(listOne, listTwo)) {
        return true;
    }

    List listOneCopy = Lists.newArrayList(listOne);
    List listTwoCopy = Lists.newArrayList(listTwo);
    listOneCopy.removeAll(listTwoCopy);

    return CollectionUtils.isNotEmpty(listOneCopy);
}

private boolean isNullLists(List listOne, List listTwo) {
    return listOne == null && listTwo == null;
}

private boolean hasDifferentSize(List listOne, List listTwo) {
    return (listOne == null && listTwo != null) || (listOne != null && listTwo == null) || (listOne.size() != listTwo.size());
}

Share this Post