This post will discuss how to check if two lists are equal in Java. The List may be a List of primitive types or a List of Objects. Two lists are defined to be equal if they contain exactly the same elements, in the same order.

1. Using List.equals() method

A simple solution to compare two lists of primitive types for equality is using the List.equals() method. It returns true if both lists have the same size, and all corresponding pairs of elements in both lists are equal.

Download  Run Code

Output:

Both lists are equal

2. Using Objects.equals() method

Alternatively, we can use the Objects.equals() method for comparing two lists of primitive types in Java. It returns true if the arguments are equal to each other, and false otherwise. The advantage of using this method is that it is null-safe and there’s no need to explicitly handle nulls.

Download  Run Code

Output:

Both lists are equal

 
It is worth noting that Objects.equals() calls List.equals() method internally.

You can also use the Objects.deepEquals() method that returns true if the arguments are “deeply” equal to each other and false otherwise.

3. Check equality in List of objects

To compare two lists of objects in Java, you can use either List.equals(…) or Objects.equals(…) methods, as discussed above. However, you would also need to override equals and hashCode methods for that object in Java. The following program demonstrates it:

Download  Run Code

Output:

Both lists are equal

That’s all about checking if two lists are equal in Java.