The List interface in Java provides methods to be able to compare two Lists and find the common and missing items from the lists.
Compare two unsorted lists for equality
If you want to check that two lists are equal, i.e. contain the same items and and appear in the same index then we can use:
As you can see the
equals() method compares the items and their location in the list.
Compare two sorted lists
Do two lists contain same items?
To compare two lists for equality just in terms of items regardless of their location, we need to use the
sort() method from the
Compare two lists, find differences
List interface also provides methods to find differences between two lists.
removeAll() method compares two lists and removes all the common items. What’s left is the additional or missing items.
For example when we compare two lists,
listTwo and we want to find out what items are missing from
listTwo we use:
Likewise, if we used:
We would get:
Compare two lists, find common items
retainAll() method only keeps the items that are common in both lists. For example: