In this tutorial we will learn how to compare two ArrayList. We would be using contains() method for comparing two elements of different ArrayList.
public boolean contains(Object o)
It returns true if the list contains the Object o else it returns false.
Example:
In this example we have two ArrayList al1
and al2
of String type. We have compared these ArrayLists using contains()
method and stored the comparison result in third ArrayList (al3
and al4
).
package beginnersbook.com; import java.util.ArrayList; public class Details { public static void main(String [] args) { ArrayList<String> al1= new ArrayList<String>(); al1.add("hi"); al1.add("How are you"); al1.add("Good Morning"); al1.add("bye"); al1.add("Good night"); ArrayList<String> al2= new ArrayList<String>(); al2.add("Howdy"); al2.add("Good Evening"); al2.add("bye"); al2.add("Good night"); //Storing the comparison output in ArrayList<String> ArrayList<String> al3= new ArrayList<String>(); for (String temp : al1) al3.add(al2.contains(temp) ? "Yes" : "No"); System.out.println(al3); //Storing the comparison output in ArrayList<Integer> ArrayList<Integer> al4= new ArrayList<Integer>(); for (String temp2 : al1) al4.add(al2.contains(temp2) ? 1 : 0); System.out.println(al4); } }
Output:
[No, No, No, Yes, Yes] [0, 0, 0, 1, 1]
What is the logic in above code?
If the first element of ArrayList al1 is present in al2
then ArrayList al3
would be having “Yes” and al4
would be having “1” However if the element is not present “No” would be stored in al3
and 0 would be in al4
.
Minhazur says
Hello sir,
What is temp here??
manoj kumar says
its only a reference variable that is using for the printing of arraylist content.
Rajeev says
Hi Chaithanya,
can you explain these following code..Actually I didn’t understand what you are trying to explain..
ArrayList al3= new ArrayList();
for (String temp : al1)
al3.add(al2.contains(temp) ? “Yes” : “No”);
System.out.println(al3);
Thanks in Advance
Arvind says
Thats the enhanced for loop introduced in Java 5.0.
Shilpa says
A new arraylist is initialized as al3.
The al1 ArrayList is stored in temp using the for each loop.
Then the content of temp is compared with the 2nd ArrayList al2,
If present YES else NO. This is done by using ternary condition.
That Yes or No is now added to the al3 and finally output is displayed.
Sam says
How can we use Question mark and colon between yes and no without using inverted commas?
Secondly error comes when i remove question mark.
NAVEEN SAI says
ArrayList al3= new ArrayList();
for (String temp : al1)
al3.add(al2.contains(temp) ? “Yes” : “No”);
System.out.println(al3);
>>>>> this is advanced for loop. so after iterating it stores the values in temp and later we are comparing arraylist al2 and temp(reference variable)..i.e we are comparing al2 &temp