Compare two ArrayLists in java

In this tutorial, we will see how to compare the elements of two ArrayLists in java. We must use the method contains()  and equals() to compare two elements from different ArrayList.

Both; method returns true if the list contains the o object otherwise false.

Compare two ArrayLists using the contains()

In this example, we have two ArrayLists L1 and L2 of type String. We should compare these two ArrayLists using contains() and save the results to another ArrayList L3.

import java.util.ArrayList; 

public class ArrayListComparison{

public static void main(String[] args) {

// Create an ArrayList< String> L1
ArrayList< String> L1 = new ArrayList< String> ();

//add elements to L1
L1.add("2");
L1.add("8");
L1.add("1");
L1.add("9");
L1.add("7");

System.out.println("L1 Elements:");
for(String o:L1)
System.out.println(o);

// Create an ArrayList< String> L2
ArrayList< String> L2 = new ArrayList< String> ();

//add elements to L2
L2.add("2");
L2.add("4");
L2.add("1");
L2.add("9");
L2.add("5");

System.out.println("L2:"Elements);
for(String o:L1)
System.out.println(o);

//Compare and store results in L3
ArrayList< String> L3 = new ArrayList< String> ();
for(String o:L1){
if(L2.contains(o))
L3.add("1");
else
L3.add("0");
}

System.out.println("L3 = "+L3);
}
}
Runtime:

L1:
2
8
1
9
7
L2:
2
4
1
9
5
L3 = [1, 0, 1, 1, 0]
If the object in L1 is in the  same  position in L2 then, L3 adds "1", in the opposite case L3  appends "0".

Compare two ArrayLists using the equals()

The equals() of the ArrayList class tests the equality of two objects.


import java.util.ArrayList; 

public class ArrayListComparison{

public static void main(String[] args) {

// Create an ArrayList< String> L1
ArrayList< String> L1 = new ArrayList< String> ();

//add elements to L1
L1.add("a");
L1.add("c");
L1.add("b");
L1.add("d");
L1.add("e");

System.out.println("L1 element:");
for(String o:L1)
System.out.println(o);

// Create an ArrayList< String> L2
ArrayList< String> L2 = new ArrayList< String> ();

//add elements to L2
L2.add("a");
L2.add("d");
L2.add("b");
L2.add("f");
L2.add("e");

System.out.println("L2 element:");
for(String o:L1)
System.out.println(o);

//Compare and store results in L3
ArrayList< String> L3 = new ArrayList< String> ();
for(int i=0; i< L1.size(); i++){
if(L1.get(i).equals(L2.get(i)))
L3.add("1");
else
L3.add("0");
}

System.out.println("L3 = "+L3);
}
}
Runtime:

L1:
a
c
b
d
e
L2 element:
a
d
b
f
e< br />L3 = [1, 0, 1, 0, 1]
You can also use the operator ==  instead of the equals():

if(L1.get(i)==L2.get(i))