Home Tutorial Java Collections Arraylist Display Common Elements from two ArrayLists in Java

 
 

Share on Google+Share on Google+
Display Common Elements from two ArrayLists in Java
Posted on: October 24, 2009 at 12:00 AM
Advertisement
In this section, we are going to compare two array lists and display the common elements from both of them.

Display Common Elements from two ArrayLists in Java

In this section, we are going to compare two array lists and display the common elements from both of them. To show the common elements from the two list, we have created two array lists a1 and a2 and add some elements to both of them. Then we have created a condition according to list sizes and display the common one.

Here is the code:

import java.util.*;

public class DisplayCommonElement{
  public static void main(String[]args){
    ArrayList a1 = new ArrayList();
    ArrayList a2 = new ArrayList();
     a1.add("a");
     a1.add("b");
     a1.add("c");
        
    a2.add("a");
    a2.add("b");
    a2.add("c")
    a2.add("d");
    a2.add("e");
        int array1Size = a1.size();
        int array2Size = a2.size();
        if (a1.size() > a2.size()) {
            int k = 0;
            for (int i = 0; i < a2.size(); i++)            {
                if (((String)a1.get(i)).equals((String)a2.get(i)))  {
                    System.out.println((String)a2.get(i));
                }
                k = i;
            }
           }
        else {
           int k = 0;
            for (int i = 0; i < a1.size(); i++) {
                if (((String)a1.get(i)).equals((String)a2.get(i))) {
                    System.out.println((String)a1.get(i));
                }
                k = i;
            }
         }
  }
}

Output

a
b
c
Advertisement

Related Tags for Display Common Elements from two ArrayLists in Java:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 24, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com