The Wayback Machine - https://web.archive.org/web/20240622171600/https://www.geeksforgeeks.org/find-common-elements-in-two-arraylists-in-java/
Open In App

Find common elements in two ArrayLists in Java

Last Updated : 05 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report


Prerequisite: ArrayList in Java

Given two ArrayLists, the task is to print all common elements in both the ArrayLists in Java .

Examples:

Input: List1 = ["Hii", "Geeks", "for", "Geeks"], 
       List2 = ["Hii", "Geeks", "Gaurav"]
Output: [Hii, Geeks, Geeks]

Input: List1 = ["a", "b", "c", "d", "e", "f"], 
       List2 = ["b", "d", "e", "h", "g", "c"]
Output:[b, c, d, e]
  1. Using Collections.retainAll() method

    Syntax:

    Collections1.retainAll(Collections2)
    
    This method keeps only the common elements
    of both Collection in Collection1.
    

    Approach:

    1. Get the two ArrayLists.
    2. Find the common elements in both the Lists using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1.
    3. The List 1 now contains the common elements only.

    Below is the implementation of the above approach:
    Program: By modifying the contents of List1.




    // Java Program to find common elements
    // in two ArrayLists
    // Using retainAll() method
      
    // import ArrayList package
    import java.util.ArrayList;
      
    public class GFG {
      
        // main method
        public static void main(String[] args)
        {
      
            // create ArrayList list1
            ArrayList<String>
                list1 = new ArrayList<String>();
      
            // Add values in ArrayList
            list1.add("Hii");
            list1.add("Geeks");
            list1.add("for");
            list1.add("Geeks");
      
            // print list 1
            System.out.println("List1: "
                               + list1);
      
            // Create ArrayList list2
            ArrayList<String>
                list2 = new ArrayList<String>();
      
            // Add values in ArrayList
            list2.add("Hii");
            list2.add("Geeks");
            list2.add("Gaurav");
      
            // print list 2
            System.out.println("List2: "
                               + list2);
      
            // Find the common elements
            list1.retainAll(list2);
      
            // print list 1
            System.out.println("Common elements: "
                               + list1);
        }
    }

    
    

    Output:

    List1: [Hii, Geeks, for, Geeks]
    List2: [Hii, Geeks, Gaurav]
    Common elements: [Hii, Geeks, Geeks]
    

    Program 2: By retaining the contents of List1.




    // Java Program to find common elements
    // in two ArrayLists
    // Using retainAll() method
      
    // import ArrayList package
    import java.util.ArrayList;
      
    public class GFG {
      
        // main method
        public static void main(String[] args)
        {
      
            // create ArrayList list1
            ArrayList<String>
                list1 = new ArrayList<String>();
      
            // Add values in ArrayList
            list1.add("Hii");
            list1.add("Geeks");
            list1.add("for");
            list1.add("Geeks");
      
            // print list 1
            System.out.println("List1: "
                               + list1);
      
            // Create ArrayList list2
            ArrayList<String>
                list2 = new ArrayList<String>();
      
            // Add values in ArrayList
            list2.add("Hii");
            list2.add("Geeks");
            list2.add("Gaurav");
      
            // print list 2
            System.out.println("List2: "
                               + list2);
      
            // Create ArrayList list3
            ArrayList<String>
                list3 = new ArrayList<String>(list1);
      
            // Store the comparison output
            // in ArrayList list3
            list3.retainAll(list2);
      
            // print list 3
            System.out.println("Common elements: "
                               + list3);
        }
    }

    
    

    Output:

    List1: [Hii, Geeks, for, Geeks]
    List2: [Hii, Geeks, Gaurav]
    Common elements: [Hii, Geeks, Geeks]
    
  2. Using Stream filter

    Syntax:

    list1.stream()
        .filter(list2::contains)
        .collect(Collectors
        .toList()));
    
    This method returns element if found in second list.
    

    Approach:

    1. First create two ArrayList and add values of list.
    2. Convert the ArrayList to Stream using stream() method.
    3. Set the filter condition to be distinct using contains() method.
    4. Collect the filtered values as List using collect() method. This list will be return common element in both list.
    5. Print list3

    Below is the implementation of the above approach:

    Program:




    // Java Program to find common elements
    // in two ArrayLists
    // Using  Stream filter method
      
    // import ArrayList package
    import java.util.*;
    import java.util.stream.*;
      
    public class GFG {
      
        // main method
        public static void main(String[] args)
        {
      
            // create ArrayList list1
            ArrayList<String>
                list1 = new ArrayList<String>();
      
            // Add values in ArrayList
            list1.add("Hii");
            list1.add("Geeks");
            list1.add("for");
            list1.add("Geeks");
      
            // print list 1
            System.out.println("List1: "
                               + list1);
      
            // Create ArrayList list2
            ArrayList<String>
                list2 = new ArrayList<String>();
      
            // Add values in ArrayList
            list2.add("Hii");
            list2.add("Geeks");
            list2.add("Gaurav");
      
            // print list 2
            System.out.println("List2: "
                               + list2);
      
            // Find common elements
            System.out.print("Common elements: ");
            System.out.println(list1.stream()
                                   .filter(list2::contains)
                                   .collect(Collectors
                                                .toList()));
        }
    }

    
    

    Output:

    List1: [Hii, Geeks, for, Geeks]
    List2: [Hii, Geeks, Gaurav]
    Common elements: [Hii, Geeks, Geeks]
    
  3. Naive approach:
    1. First create two ArrayList and add values of list.
    2. Create a temporary ArrayList to contain common elements.
    3. Iterate through the list1 and check if that element is present in the list2 using ArrayList.contains() method.
    4. If found, add it to the list3
    5. Print the common elements from list3

    Below is the implementation of the above approach:




    // Java Program to find common elements
    // in two ArrayLists
    // Using  Stream filter method
      
    // import ArrayList package
    import java.util.ArrayList;
      
    public class GFG {
      
        // main method
        public static void main(String[] args)
        {
      
            // create ArrayList list1
            ArrayList<String>
                list1 = new ArrayList<String>();
      
            // Add values in ArrayList
            list1.add("Hii");
            list1.add("Geeks");
            list1.add("for");
            list1.add("Geeks");
      
            // print list 1
            System.out.println("List1: "
                               + list1);
      
            // Create ArrayList list2
            ArrayList<String>
                list2 = new ArrayList<String>();
      
            // Add values in ArrayList
            list2.add("Hii");
            list2.add("Geeks");
            list2.add("Gaurav");
      
            // print list 2
            System.out.println("List2: "
                               + list2);
      
            // Create ArrayList list3
            ArrayList<String>
                list3 = new ArrayList<String>();
      
            // Find common elements
            // while iterating through list1
            for (String temp : list1) {
      
                // Check if the element is
                // present in list2 or not
                if (list2.contains(temp)) {
      
                    // Since present, add it to list3
                    list3.add(temp);
                }
            }
      
            // print common elements from list 3
            System.out.println("Common elements: "
                               + list3);
        }
    }

    
    

    Output:

    List1: [Hii, Geeks, for, Geeks]
    List2: [Hii, Geeks, Gaurav]
    Common elements: [Hii, Geeks, Geeks]
    


  4. Previous Article
    Next Article

Similar Reads

Join two ArrayLists in Java
Given two ArrayLists in Java, the task is to join these ArrayLists. Examples: Input: ArrayList1: [Geeks, For, ForGeeks], ArrayList2: [GeeksForGeeks, A computer portal] Output: ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal] Input: ArrayList1: [G, e, e, k, s], ArrayList2: [F, o, r, G, e, e, k, s] Output: ArrayList: [G, e, e, k, s
2 min read
Iterating over ArrayLists in Java
ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. With the introduction and upgradations in java versions
5 min read
How to Split an ArrayList in Multiple Small ArrayLists?
In Java, ArrayList is a pre-defined class of the Java collection framework, and it can be used to add the elements dynamically. One more special feature is that it can shrink the size dynamically to add or remove the elements from the ArrayList. In this article, we will discuss how to split an ArrayList into multiple small ArrayLists. Step-by-Step
2 min read
Java Program to Find Common Elements Between Two Arrays
Given two arrays and our task is to find their common elements. Examples: Input: Array1 = ["Article", "for", "Geeks", "for", "Geeks"], Array2 = ["Article", "Geeks", "Geeks"]Output: [Article,Geeks] Input: Array1 = ["a", "b", "c", "d", "e", "f"], Array2 = ["b", "d", "e", "h", "g", "c"]Output: [b, c, d, e] Using Iterative Methods Approach: Get the two
4 min read
How to Find the Longest Common Prefix of Two Strings in Java?
In this article, we will find the longest common prefix of two Strings in Java. Examples: Input: String 1= geeksforgeeks, String 2 = geezerOutput: “gee” Input: String 1= flower, String 2 = flightOutput: “fl” Methods to Find the Longest common Prefix of two Strings in JavaBelow are the methods by which we can find the longest common prefix of two St
4 min read
Print common characters of two Strings in alphabetical order
Given two strings, print all the common characters in lexicographical order. If there are no common letters, print -1. All letters are lower case. Examples: Input : string1 : geeks string2 : forgeeks Output : eegks Explanation: The letters that are common between the two strings are e(2 times), k(1 time) and s(1 time). Hence the lexicographical out
6 min read
Java Program to Count of Array elements greater than all elements on its left and at least K elements on its right
Given an array A[ ] consisting of N distinct integers, the task is to find the number of elements which are strictly greater than all the elements preceding it and strictly greater than at least K elements on its right. Examples: Input: A[] = {2, 5, 1, 7, 3, 4, 0}, K = 3 Output: 2 Explanation: The only array elements satisfying the given conditions
7 min read
10 Most Common Mistakes That Java Developers Make
If you’re working on any new programming language, there might be certain phases where you can get stuck. This eventually leads any developer to make minor-major errors and creates a roadblock towards their learning curve. Not to forget, as much as you’ll be making mistakes, you’ll achieve excellence. Besides this, learning Java is no different tas
9 min read
5 Most Common Java Pitfalls
1. Not understanding that String is an immutable class: The Java String class is immutable (Unmodifiable). This is because String objects are cached in a String pool. The object that a String is referencing to can change, but the String objects themselves cannot. Example: Java Code public class Main { public static void main(String[] args) { String
5 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
three90RightbarBannerImg