Collections

Java compare ArrayList example

Java compare ArrayList example shows how to compare ArrayList objects in Java. Example also shows how to compare ArrayList to check if they are equal as well as getting missing or common elements from two ArrayList objects.

How to compare ArrayList in Java?

There are many ways in which we can compare two ArrayList objects. For example we may want to check if they are equal, or we may want to know what are the common elements or elements contained in one ArrayList but missing from other.

1. Compare two ArrayList objects to check if they are equal

Below given code compares two ArrayList and checks if they are equal.

Output

If both ArrayList objects have same elements but in different order, above code will return false. If you want to compare ArrayList elements regardless of the order, sort them before comparing like given below.

Output

Note: if the ArrayList objects you want to compare contains objects of a custom class, then the class must override equals and hashCode methods as given below. Additionally if you sort ArrayList using sort method, the custom class also needs to implement Comparable interface and define compareTo method.

Below given example has Emp class having empId as primary key, so if two object has same empId, they will be considered as equal. Change the equals and hashCode methods according to your class structure.

Output

2. Compare and get common elements of two ArrayList objects

If you want to compare two ArrayList objects and get all the common elements between two, you can use retainAll method as given below.

Output

Note: Make sure to copy ArrayList first so that original list remains unchanged. Again, for the ArrayList having custom class objects, implement equals and hashCode methods in your custom class as given in above Emp class example.

3. Compare and get missing elements from another ArrayList

Instead of retaining all the elements contained in other ArrayList from first ArrayList object, we are going to remove all the elements contained in other ArrayList. That will give us all the elements which are not present in other ArrayList as given below.

Output

Note: Make sure to copy ArrayList first so that original list remains unchanged. Again, for the ArrayList having custom class objects, implement equals and hashCode methods in your custom class as given in above Emp class example.

Reference: ArrayList JavaDoc (Java 8)

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.