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:
import java.util.Arrays; import java.util.List; public class CompareTwoLists { public static void main[String[] args] { List listOne = Arrays.asList["a", "b", "c"]; List listTwo = Arrays.asList["a", "b", "c"]; List listThree = Arrays.asList["c", "a", "b"]; boolean isEqual = listOne.equals[listTwo]; System.out.println[isEqual]; isEqual = listOne.equals[listThree]; System.out.println[isEqual]; } }Output:
true falseAs you can see the equals[] method compares the items and their location in the list.
Related:
- How to loop through an ArrayList in Java
- How to remove duplicates from a list
- How to convert list to array in Java
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 Collections[] class.
For example:
import java.util.Arrays; import java.util.Collections; import java.util.List; public class CompareTwoLists { public static void main[String[] args] { List listOne = Arrays.asList["b", "c", "a"]; List listTwo = Arrays.asList["a", "c", "b"]; List listThree = Arrays.asList["c", "a", "b"]; Collections.sort[listOne]; Collections.sort[listTwo]; Collections.sort[listThree]; boolean isEqual = listOne.equals[listTwo]; System.out.println[isEqual]; isEqual = listOne.equals[listThree]; System.out.println[isEqual]; } }Output:
true trueCompare two lists, find differences
The List interface also provides methods to find differences between two lists.
The removeAll[] method compares two lists and removes all the common items. Whats left is the additional or missing items.
For example when we compare two lists, listOne and listTwo and we want to find out what items are missing from listTwo we use:
Output:
Missing items from listTwo [3]Likewise, if we used:
listTwo.removeAll[listOne]; System.out.println["Missing items from listOne " + listTwo];We would get:
Missing items from listOne [6, 7]Compare two lists, find common items
The retainAll[] method only keeps the items that are common in both lists. For example:
public class CompareTwoArrayLists { public static void main[String[] args] { ArrayList listOne = new ArrayList[Arrays.asList[1, 2, 3, 4, 5]]; ArrayList listTwo = new ArrayList[Arrays.asList[1, 2, 4, 5, 6, 7]]; listOne.retainAll[listTwo]; System.out.println["Common items in both lists " + listOne]; } }Output:
Common items in both lists [1, 2, 4, 5]Share this on: Twitter LinkedIn