Compare two custom List in Java

In this tutorial, we are going to see how to compare two ArrayList in Java. You can compare two ArrayLists using the equals[] method of the ArrayList class, this method accepts a list object as a parameter, compares it to the current object, if there is a match, it returns TRUE and otherwise, it returns FALSE.
 

Java Program to Compare Two ArrayList: import java.util.ArrayList; public class Main { public static void main[String[] args] { ArrayList list1 = new ArrayList[]; list1.add["Java"]; list1.add["PHP"]; list1.add["Python"]; list1.add["Pascal"]; ArrayList list2 = new ArrayList[]; list2.add["Java"]; list2.add["PHP"]; list2.add["Python"]; list2.add["Pascal"]; if[list1.equals[list2]] System.out.println["The two ArrayList are equal."]; else System.out.println["The two ArrayList are not equal."]; } }

Output:

The two arraylists are equal. [wbcr_php_snippet id=”598″ title=”GetPreviousPost” postid= “1796”] [wbcr_php_snippet id=”125″ title=”GetPreviousPost” category_id= “9”]

Java provides a method for comparing two Array List. The ArrayList.equals[] is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal.

Example:

Input : ArrayList1 = [1, 2, 3, 4], ArrayList2 = [1, 2, 3, 4] Output: Array List are equal Input : ArrayList1 = [1, 2, 3, 4], ArrayList2 = [4, 2, 3, 1] Output: Array List are not equal

Syntax:

boolean equals[Object o]

Parameters: This function has a single parameter which is an object to be compared for equality.

Returns: This method returns True if Array lists are equal.



Implementation:

import java.util.ArrayList;

    public static void main[String[] args]

        ArrayList ArrayList1

            = new ArrayList[];

        ArrayList ArrayList2

            = new ArrayList[];

        ArrayList1.add["item 1"];

        ArrayList1.add["item 2"];

        ArrayList1.add["item 3"];

        ArrayList1.add["item 4"];

        ArrayList2.add["item 1"];

        ArrayList2.add["item 2"];

        ArrayList2.add["item 3"];

        ArrayList2.add["item 4"];

        System.out.println[" ArrayList1 = " + ArrayList2];

        System.out.println[" ArrayList1 = " + ArrayList1];

        if [ArrayList1.equals[ArrayList2] == true] {

            System.out.println[" Array List are equal"];

            System.out.println[" Array List are not equal"];

            "\n Lets insert one more item in Array List 1"];

        ArrayList1.add["item 5"];

        System.out.println[" ArrayList1 = " + ArrayList1];

        System.out.println[" ArrayList = " + ArrayList2];

        if [ArrayList1.equals[ArrayList2] == true] {

            System.out.println[" Array List are equal"];

            System.out.println[" Array List are not equal"];

Output ArrayList1 = [item 1, item 2, item 3, item 4] ArrayList1 = [item 1, item 2, item 3, item 4] Array List are equal Lets insert one more item in Array List 1 ArrayList1 = [item 1, item 2, item 3, item 4, item 5] ArrayList = [item 1, item 2, item 3, item 4] Array List are not equal

Time Complexity: O[N], where N is the length of the Array list.


This post will discuss how to compare two lists for equality in Java, ignoring the order. The List may be a List of primitive types or a List of Objects. Two lists are defined to be equal if they contain exactly the same elements in equal quantity each, in any order.

For example, [1, 2, 3] and [2, 1, 3] are considered equal, while [1, 2, 3] and [2, 4, 3] are not. The elements’ count also matters, hence, [1, 2, 3, 1] and [2, 1, 3, 2] are not treated equally. If the elements count doesn’t matter, you can convert both lists to a Set and compare them using the .equals[] method of the Set interface.

1. Sorting

A simple solution is to sort both lists and then compare them using the .equals[] method of the List interface. Note that this solution is not linear, and has O[n.log[n]] time complexity. It is not suitable for large lists.

To improve efficiency, it is recommended to first check if both lists have the same size or not. Also before sorting both lists, create their copy to avoid destroying the original order of both lists. Both copying and sorting steps can be done efficiently using Streams API, as shown below.

import java.util.stream.Collectors;

    public static boolean isEqualIgnoringOrder[List x, List y] {

        if [x.size[] != y.size[]] {

        x = x.stream[].sorted[].collect[Collectors.toList[]];

        y = y.stream[].sorted[].collect[Collectors.toList[]];

    public static void main[String[] args]

        List x = List.of[1, 2, 3];

        List y = List.of[2, 3, 1];

        boolean isEqual = isEqualIgnoringOrder[x, y];

            System.out.println["Both lists are equal"];

            System.out.println["Both lists are not equal"];

Download  Run Code

Output:
Both lists are equal

2. Using Multiset

Another solution is to convert both lists to multiset and compare the multiset, which compares elements regardless of their order and also preserves the count of duplicate elements. The following solution demonstrates this using Guava’s Multiset.

import com.google.common.collect.ImmutableMultiset;

    public static boolean isEqualIgnoringOrder[List x, List y] {

        if [x.size[] != y.size[]] {

        return ImmutableMultiset.copyOf[x].equals[ImmutableMultiset.copyOf[y]];

    public static void main[String[] args]

        List x = List.of[1, 2, 2];

        List y = List.of[1, 2, 1];

        boolean isEqual = isEqualIgnoringOrder[x, y];

            System.out.println["Both lists are equal"];

            System.out.println["Both lists are not equal"];

Download Code

Output:
Both lists are not equal

3. Apache Commons Lang Library

Finally, Apache Commons Lang Library offers the CollectionUtils.isEqualCollection[] method, which returns true if the given Collections contain exactly the same elements with exactly the same cardinalities.

import org.apache.commons.collections4.CollectionUtils;

    public static void main[String[] args]

        List x = List.of[1, 2, 3];

        List y = List.of[2, 3, 1];

        boolean isEqual = CollectionUtils.isEqualCollection[x, y];

            System.out.println["Both lists are equal"];

            System.out.println["Both lists are not equal"];

Download Code

Output:
Both lists are equal

4. Check equality in List of objects

To compare two lists of objects using any of the above methods, you need to override equals and hashCode methods for that object in Java. The following program demonstrates it:

import org.apache.commons.collections4.CollectionUtils;

    President[String name, int age] {

    public boolean equals[Object o] {

        if [this == o] return true;

        if [o == null || getClass[] != o.getClass[]] return false;

        President person = [President] o;

        return age == person.age && Objects.equals[name, person.name];

        return Objects.hash[name, age];

    public static void main[String[] args]

        List x = List.of[

                new President["Trump", 75],

                new President["Obama", 60],

                new President["Trump", 75]];

        List y = List.of[

                new President["Obama", 60],

                new President["Trump", 75],

                new President["Trump", 75]];

        boolean isEqual = CollectionUtils.isEqualCollection[x, y];

            System.out.println["Both lists are equal"];

            System.out.println["Both lists are not equal"];

Download Code

Output:
Both lists are equal

That’s all about comparing two lists for equality in Java, ignoring the order.


Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂


Video liên quan

Chủ Đề