1. Introduction

In Java, finding the intersection of two lists means to find out all the common elements between them. In this tutorial, we will explore how to get the intersection of two lists in Java using different methods like retainAll() and stream API.

2. Program Steps

1. Import the necessary classes.

2. Create two Lists with some common and distinct elements.

3. Use the retainAll() method to find the intersection of the lists.

4. Alternatively, use the stream() API and filter() method to find the intersection.

3. Code Program

// Step 1: Importing necessary classes
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ListIntersection {

    public static void main(String[] args) {

        // Step 2: Creating two Lists with some common and distinct elements
        List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        List<Integer> list2 = new ArrayList<>(Arrays.asList(3, 4, 5, 6, 7));

        // Printing the original lists
        System.out.println("List1: " + list1);
        System.out.println("List2: " + list2);

        // Step 3: Using retainAll() method to find the intersection
        List<Integer> intersection = new ArrayList<>(list1);
        intersection.retainAll(list2);
        System.out.println("Intersection using retainAll: " + intersection);

        // Step 4: Using stream API to find the intersection
        List<Integer> streamIntersection = list1.stream()
                                                .filter(list2::contains)
                                                .collect(Collectors.toList());
        System.out.println("Intersection using stream: " + streamIntersection);
    }
}

Output:

List1: [1, 2, 3, 4, 5]
List2: [3, 4, 5, 6, 7]
Intersection using retainAll: [3, 4, 5]
Intersection using stream: [3, 4, 5]

4. Step By Step Explanation

Step 1: Import the necessary classes and interfaces.

Step 2: Define two List objects, list1 and list2, which contain both common and distinct elements.

Step 3:

– Create a new ArrayList named intersection and initialize it with the elements of list1.

– Use the retainAll() method on intersection, passing list2 as the parameter. This method retains only the elements in intersection that are also contained in list2.

– Print the intersection List, which now contains the common elements between list1 and list2.

Step 4: Alternatively, you can also use the stream() API and filter() method to find the intersection of the two lists.

– Use stream() on list1 and filter() it by checking if list2 contains each element.

– Collect the result into a new List called streamIntersection.

– Print the streamIntersection List.