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

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


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

// the function, given these two lists, should return true


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);

    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