DEV Community

aryan
aryan

Posted on • Edited on • Originally published at java8net.blogspot.com

1

How to compare two ArrayList in Java?

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay