Pre Exam Test Practice (SSC | Banking | IAS | GATE | State Level | CLAT | Railways | Insurance | Teaching Exams | NDA | Defence | IES |State Exam )

Organizational Research By

Surprising Reserch Topic

How to compare two ArrayList in Java

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.


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).

import java.util.ArrayList;
public class Details
     public static void main(String [] args)
          ArrayList<String> al1= new ArrayList<String>();
          al1.add("How are you");
          al1.add("Good Morning");
          al1.add("Good night");

          ArrayList<String> al2= new ArrayList<String>();
          al2.add("Good Evening");
          al2.add("Good night");

          //Storing the comparison output in ArrayList
          ArrayList<String> al3= new ArrayList<String>();
          for (String temp : al1)
              al3.add(al2.contains(temp) ? "Yes" : "No");

          //Storing the comparison output in ArrayList
          ArrayList<Integer> al4= new ArrayList<Integer>();
          for (String temp2 : al1)
               al4.add(al2.contains(temp2) ? 1 : 0);


[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 al3would 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.

asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes

Related Hot Questions

Government Jobs Opening