java1 Min Read

Java - Union and Intersection of two lists

Gorav Singal

July 04, 2019

TL;DR

Use Java's retainAll() for intersection and addAll() with a Set for union to efficiently combine or find common elements between two lists.

Java - Union and Intersection of two lists

Suppose you have two lists, and you want Union and Intersection of those two lists.

Example

Input:

list1: [1, 2, 3, 4]
list2: [3, 4, 5, 6]

union(list1, list2): [1, 2, 3, 4, 5, 6]
intersection(list1, list2): [3, 4]

Solution

See the java code for multiple solutions:

public static List<Integer> getIntersection_1(List<Integer> l1, List<Integer> l2) {
    return l1.stream().filter(l2::contains).collect(Collectors.toList());
}

public static List<Integer> getIntersection_2(List<Integer> l1, List<Integer> l2) {
    Set<Integer> s1 = new HashSet<>(l1);
    s1.retainAll(l2);
    return new ArrayList<>(s1);
}

public static List<Integer> getIntersection_3(List<Integer> l1, List<Integer> l2) {
    List<Integer> list = new ArrayList<Integer>();

    for (Integer i : l1) {
        if(l2.contains(i)) {
            list.add(i);
        }
    }

    return list;
}

public static List<Integer> getUnion_1(List<Integer> l1, List<Integer> l2) {
    Set<Integer> result = new HashSet<Integer>();

    result.addAll(l1);
    result.addAll(l2);

    return new ArrayList<Integer>(result);
}

public static List<Integer> getUnion_2(List<Integer> l1, List<Integer> l2) {
    Set<Integer> s1 = new HashSet<>(l1);
    s1.addAll(l2);
    return new ArrayList<>(s1);
}
Share

Related Posts

Linkage Error Loader Constraint Violation - JUnit test case development issue

Linkage Error Loader Constraint Violation - JUnit test case development issue

Its good to write unit tests cases, and this part is mostly forgotten by…

How to mock a constructor - Junit test case development issues

How to mock a constructor - Junit test case development issues

While writing JUnit test cases, we encounter cases like we want to initialize a…

Java Log4j Logger - Programmatically Initialize JSON logger with customized keys in json logs

Java Log4j Logger - Programmatically Initialize JSON logger with customized keys in json logs

Introduction Java log4j has many ways to initialize and append the desired…

How to Solve Spring Okta/Saml issue of SAML message intended destination endpoint did not match the recipient endpoint

How to Solve Spring Okta/Saml issue of SAML message intended destination endpoint did not match the recipient endpoint

Introduction I was trying to integrate Okta with Spring, and when I deploy the…

Spring - Learn Multiple Ways to use PackageScan Annotation

Spring - Learn Multiple Ways to use PackageScan Annotation

Introduction In this post, we will see multiple ways to use annotation…

Spring Boot - Fixing Autowire Bean Not found

Spring Boot - Fixing Autowire Bean Not found

Introduction In a Spring boot app, we tend to use annotation, so that Spring…

Latest Posts

AI Video Generation in 2025 — Models, Costs, and How to Build a Cost-Effective Pipeline

AI Video Generation in 2025 — Models, Costs, and How to Build a Cost-Effective Pipeline

AI video generation went from “cool demo” to “usable in production” in 2024-202…

AI Models in 2025 — Cost, Capabilities, and Which One to Use

AI Models in 2025 — Cost, Capabilities, and Which One to Use

Choosing the right AI model is one of the most impactful decisions you’ll make…

AI Image Generation in 2025 — Models, Costs, and How to Optimize Spend

AI Image Generation in 2025 — Models, Costs, and How to Optimize Spend

Generating one image with AI costs between $0.002 and $0.12. That might sound…

AI Coding Assistants in 2025 — Every Tool Compared, and Which One to Actually Use

AI Coding Assistants in 2025 — Every Tool Compared, and Which One to Actually Use

Two years ago, AI coding meant one thing: GitHub Copilot autocompleting your…

AI Agents Demystified — It's Just Automation With a Better Brain

AI Agents Demystified — It's Just Automation With a Better Brain

Let’s cut through the noise. If you read Twitter or LinkedIn, you’d think “AI…

Supply Chain Security — Protecting Your Software Pipeline

Supply Chain Security — Protecting Your Software Pipeline

In 2024, a single malicious contributor nearly compromised every Linux system on…