Thursday, October 16, 2025
HomeLanguagesJavaHow to Compare two Collections in Java?

How to Compare two Collections in Java?

Java Collection provides an architecture to store and manipulate the group of objects. Here we will see how to compare Elements in a Collection in Java.

Steps:

  • Take both inputs with help of asList() function.
  • Sort them using Collections.sort() method.
  • Compare them using equals() function.
  • Print output. (true means both are equal and false means both are different)

Example 1:

Java




// Java program implementing
// Comparing elements of Collections
  
import java.util.*;
import java.io.*;
  
public class ArrayCompareExample {
  
    // main function accepting string arguments
    public static void main(String[] args)
    {
        // create listA
        ArrayList<String> listA
            = new ArrayList<>(Arrays.asList("a", "b", "c"));
  
        // create listB
        ArrayList<String> listB
            = new ArrayList<>(Arrays.asList("a", "b", "d"));
  
        // sorting both lists
        Collections.sort(listA);
        Collections.sort(listB);
  
        // Compare lists using
        // equals() method
        boolean isEqual = listA.equals(listB);
  
        // print output on screen (true or false)
        System.out.println(isEqual);
    }
}


Output

false

 

Example 2:

Java




// Java program implementing
// Comparing elements of Collections
  
import java.util.*;
import java.io.*;
  
public class ArrayCompareExample {
  
    // main function accepting string arguments
    public static void main(String[] args)
    {
        // create listA
        ArrayList<Integer> listA
            = new ArrayList<>(Arrays.asList(3, 4, 5));
  
        // create listB
        ArrayList<Integer> listB
            = new ArrayList<>(Arrays.asList(4, 5, 3));
  
        // sorting both lists
        Collections.sort(listA);
        Collections.sort(listB);
  
        // Compare lists using
        // equals() method
        boolean isEqual = listA.equals(listB);
  
        // print output on screen (true or false)
        System.out.println(isEqual);
    }
}


Output

true

 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS