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
import java.util.*;
import java.io.*;
public class ArrayCompareExample {
public static void main(String[] args)
{
ArrayList<String> listA
= new ArrayList<>(Arrays.asList( "a" , "b" , "c" ));
ArrayList<String> listB
= new ArrayList<>(Arrays.asList( "a" , "b" , "d" ));
Collections.sort(listA);
Collections.sort(listB);
boolean isEqual = listA.equals(listB);
System.out.println(isEqual);
}
}
|
Example 2:
Java
import java.util.*;
import java.io.*;
public class ArrayCompareExample {
public static void main(String[] args)
{
ArrayList<Integer> listA
= new ArrayList<>(Arrays.asList( 3 , 4 , 5 ));
ArrayList<Integer> listB
= new ArrayList<>(Arrays.asList( 4 , 5 , 3 ));
Collections.sort(listA);
Collections.sort(listB);
boolean isEqual = listA.equals(listB);
System.out.println(isEqual);
}
}
|
Last Updated :
02 Nov, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...