Java: Find Intersection of Two Lists

Finding the intersection of two lists in Java involves identifying elements that are present in both lists. This guide will cover different ways to find the intersection, including using loops, the retainAll method, and the Stream API (Java 8 and later).

Table of Contents

  1. Introduction
  2. Using Loops
  3. Using retainAll Method
  4. Using Stream API
  5. Conclusion

Introduction

In Java, lists are dynamic data structures that store elements of the same type. Finding the intersection of two lists means identifying the elements that are common to both lists. This can be useful in various scenarios, such as filtering data or finding commonalities between data sets.

Using Loops

One way to find the intersection of two lists is by iterating through each list and collecting the common elements.

Example

import java.util.ArrayList;
import java.util.List;

public class ListIntersectionExample {
    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);
        list1.add(5);

        List<Integer> list2 = new ArrayList<>();
        list2.add(3);
        list2.add(4);
        list2.add(5);
        list2.add(6);
        list2.add(7);

        List<Integer> intersection = findIntersection(list1, list2);

        System.out.println("Intersection: " + intersection);
    }

    public static List<Integer> findIntersection(List<Integer> list1, List<Integer> list2) {
        List<Integer> intersection = new ArrayList<>();
        for (Integer element : list1) {
            if (list2.contains(element)) {
                intersection.add(element);
            }
        }
        return intersection;
    }
}

Explanation

  • Two lists are created and populated with elements.
  • A loop is used to iterate through the first list.
  • If an element from the first list is found in the second list, it is added to the intersection list.

Output:

Intersection: [3, 4, 5]

Using retainAll Method

The retainAll method provided by the List interface is a convenient way to find the intersection of two lists.

Example

import java.util.ArrayList;
import java.util.List;

public class ListIntersectionExample {
    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);
        list1.add(5);

        List<Integer> list2 = new ArrayList<>();
        list2.add(3);
        list2.add(4);
        list2.add(5);
        list2.add(6);
        list2.add(7);

        list1.retainAll(list2);

        System.out.println("Intersection: " + list1);
    }
}

Explanation

  • Two lists are created and populated with elements.
  • The retainAll method is used to retain only the elements in list1 that are also in list2.

Output:

Intersection: [3, 4, 5]

Using Stream API

The Stream API (introduced in Java 8) provides a modern and concise way to find the intersection of two lists.

Example

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ListIntersectionExample {
    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);
        list1.add(5);

        List<Integer> list2 = new ArrayList<>();
        list2.add(3);
        list2.add(4);
        list2.add(5);
        list2.add(6);
        list2.add(7);

        List<Integer> intersection = list1.stream()
                                          .filter(list2::contains)
                                          .collect(Collectors.toList());

        System.out.println("Intersection: " + intersection);
    }
}

Explanation

  • Two lists are created and populated with elements.
  • A stream is created from list1.
  • The filter method is used to keep only the elements that are present in list2.
  • The collect method gathers the filtered elements into a new list.

Output:

Intersection: [3, 4, 5]

Conclusion

Finding the intersection of two lists in Java can be accomplished using various methods, each with its own advantages. Using loops provides a clear and straightforward approach, suitable for any type of list. The retainAll method offers a concise and direct way to achieve the same result with less code. The Stream API provides a modern and functional programming approach, making the code more readable and expressive. Depending on your specific use case and preferences, you can choose the method that best fits your needs.

Comments