DEV Community

loading...

How to compare two ArrayList in Java?

aryan19694946 profile image aryan Originally published at java8net.blogspot.com Updated on ・2 min read

Learn to compare two ArrayList in Java with simple examples. We will first test if two ArrayList are equal or not. If both lists are not equal, we will find the difference between lists.

The difference in the list equals another third list which contains either additional elements or missing elements.

Also, learn to find common elements between two ArrayList.

See the original post: https://www.java8net.com/2020/03/compare-two-arraylist-in-java.html

Compare two ArrayList for equality

With the help of the equals() method, we can compare two ArrayList in java and check whether they are the same or not. But, here is a condition, the order of the elements of both the ArrayList must be the same. Otherwise, it won't work. To be sure, we can sort the ArrayList (sorting can be ascending or descending) and then apply the equals() method for comparison.

Read Article to learn how to sort ArrayList in Java: https://www.java8net.com/2020/02/how-to-sort-arraylist-in-java.html

import java.util.ArrayList;

public class ArrayListExample {
public static void main(String[] args) {
ArrayList list1 = new ArrayList();
list1.add("A");
list1.add("B");
list1.add("C");
list1.add("D");
ArrayList list2 = new ArrayList();
list2.add("A");
list2.add("B");
list2.add("C");
list2.add("D");
System.out.println(list2);
System.out.println(list1.equals(list2));
}
}

If you want to learn in detail: https://www.java8net.com/2020/03/compare-two-arraylist-in-java.html

Further Reading:
https://www.java8net.com/2020/03/java-arraylist-common-program-examples.html
https://www.java8net.com/2020/03/java-sublist-from-arraylist.html
https://www.java8net.com/2020/03/how-to-remove-duplicates-from-arraylist-in-java.html
https://www.java8net.com/2020/03/iterate-arraylist-in-java.html
https://www.java8net.com/2020/03/arraylist-to-array-in-java.html

Discussion

pic
Editor guide