Display Common Elements from two ArrayLists in Java


 

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.

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

Ads