Java Compare Two Lists
To compare two lists in Java, you can use the equals()
method of the List
interface. The equals()
method compares the elements of the two lists and returns true
if the lists are equal, and false
if they are not.
Here is an example of how to compare two lists in Java:
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 compares the elements of the two lists and 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 the other list. Here is an example:
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, the containsAll()
method returns false
because list1 does not contain the element "d" that is present in list2.
I hope this helps. Let me know if you have any questions.