Skip to content

Java compare ArrayList example

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

Java ArrayList is a part of the Java Collection framework.

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 another.

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 the same elements but in a different order, the above code will return false. If you want to compare ArrayList elements regardless of the order, sort them before comparing them 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 the compareTo method.

The below given example has Emp class having empId as primary key, so if two objects have the 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 the two, you can use retainAll method as given below.

Output

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

3. Compare and get missing elements from another ArrayList

Instead of retaining all the elements contained in other ArrayList from the 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 the original list remains unchanged. Again, for the ArrayList having custom class objects, implement equals and hashCode methods in your custom class as given in the above Emp class example.

This example is a part of the Java ArrayList tutorial with examples.

Reference: ArrayList JavaDoc (Java 8)

About the author

Leave a Reply

Your email address will not be published.