W3docs

Java Compare Two Lists

To compare two lists in Java, you can use the equals() method of the List interface.

To compare two lists in Java, you can use the equals() method of the List interface. The equals() method checks if both lists contain the same elements in the exact same order, returning true if they match and false otherwise.

Here is an example of how to compare two lists in Java:


import java.util.List;
import java.util.Arrays;

List<String> list1 = Arrays.asList("a", "b", "c");
List<String> list2 = Arrays.asList("a", "b", "c");

if (list1.equals(list2)) {
    System.out.println("Lists are equal");
} else {
    System.out.println("Lists are not equal");
}

In the example above, the equals() method returns true because the lists have the same elements in the same order.

You can also use the containsAll() method to check if one list contains all the elements of another list, regardless of order. Here is an example:


import java.util.List;
import java.util.Arrays;

List<String> list1 = Arrays.asList("a", "b", "c");
List<String> list2 = Arrays.asList("a", "b", "c", "d");

if (list1.containsAll(list2)) {
    System.out.println("List1 contains all elements of list2");
} else {
    System.out.println("List1 does not contain all elements of list2");
}

In the example above, containsAll() returns false because list1 does not contain the element "d" present in list2.

Note: equals() strictly requires identical order and both objects to be List instances, while containsAll() only verifies subset membership.

I hope this helps. Let me know if you have any questions.