Java 8 – How to Merge Two Lists Using Streams

Introduction

Java 8 introduced the Stream API, which provides a powerful and flexible way to manipulate and process collections of data. One common operation you might need to perform is merging two lists into one. The Stream API makes this task straightforward and efficient, allowing you to merge two lists with ease.

In this guide, we’ll explore how to merge two lists using Java 8 streams, covering both basic and advanced scenarios.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Example 1: Merging Two Lists of Strings
    • Example 2: Merging Two Lists of Custom Objects
    • Example 3: Removing Duplicates While Merging
    • Example 4: Merging Lists and Sorting the Result
  • Conclusion

Problem Statement

When working with collections, you may need to combine two lists into a single list. The goal is to use the Stream API in Java 8 to merge two lists efficiently, while optionally removing duplicates or sorting the merged list.

Example:

  • Problem: Merging two lists into a single list and performing operations like removing duplicates or sorting the merged list.
  • Goal: Use the Stream API to merge lists and handle optional tasks like deduplication and sorting.

Solution Steps

  1. Merge Two Lists: Learn how to merge two lists of the same type.
  2. Handle Custom Objects: Extend the merging process to lists of custom objects.
  3. Remove Duplicates: Use the Stream API to remove duplicates from the merged list.
  4. Sort the Merged List: Optionally sort the merged list using the Stream API.

Java Program

Example 1: Merging Two Lists of Strings

Let’s start with a basic example of merging two lists of strings into one.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Java 8 - Merging Two Lists of Strings
 * Author: https://www.rameshfadatare.com/
 */
public class MergeListsExample1 {

    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("Amit", "Priya", "Raj");
        List<String> list2 = Arrays.asList("Suman", "Kiran", "Amit");

        // Merging two lists
        List<String> mergedList = Stream.concat(list1.stream(), list2.stream())
                                        .collect(Collectors.toList());

        System.out.println("Merged List: " + mergedList);
    }
}

Output

Merged List: [Amit, Priya, Raj, Suman, Kiran, Amit]

Explanation

  • Stream.concat(): Combines two streams into one. The two lists are converted to streams and then merged using Stream.concat().
  • collect(Collectors.toList()): Collects the merged stream into a list.

Example 2: Merging Two Lists of Custom Objects

Next, let’s merge two lists of custom objects, such as Person objects.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Java 8 - Merging Two Lists of Custom Objects
 * Author: https://www.rameshfadatare.com/
 */
public class MergeListsExample2 {

    public static void main(String[] args) {
        List<Person> list1 = Arrays.asList(new Person("Amit", 30), new Person("Priya", 25));
        List<Person> list2 = Arrays.asList(new Person("Raj", 28), new Person("Suman", 22));

        // Merging two lists of custom objects
        List<Person> mergedList = Stream.concat(list1.stream(), list2.stream())
                                        .collect(Collectors.toList());

        System.out.println("Merged List: " + mergedList);
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

Output

Merged List: [Amit (30), Priya (25), Raj (28), Suman (22)]

Explanation

  • Custom Objects: The process of merging custom objects is the same as merging strings. The merged list contains all objects from both lists.

Example 3: Removing Duplicates While Merging

If you need to remove duplicates from the merged list, you can use the distinct() method.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Java 8 - Merging Lists and Removing Duplicates
 * Author: https://www.rameshfadatare.com/
 */
public class MergeListsExample3 {

    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("Amit", "Priya", "Raj");
        List<String> list2 = Arrays.asList("Suman", "Kiran", "Amit");

        // Merging two lists and removing duplicates
        List<String> mergedList = Stream.concat(list1.stream(), list2.stream())
                                        .distinct()
                                        .collect(Collectors.toList());

        System.out.println("Merged List without Duplicates: " + mergedList);
    }
}

Output

Merged List without Duplicates: [Amit, Priya, Raj, Suman, Kiran]

Explanation

  • distinct(): Removes duplicates from the merged stream, ensuring that each element appears only once in the final list.

Example 4: Merging Lists and Sorting the Result

You can also sort the merged list after combining the two lists.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Java 8 - Merging and Sorting Lists
 * Author: https://www.rameshfadatare.com/
 */
public class MergeListsExample4 {

    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("Amit", "Priya", "Raj");
        List<String> list2 = Arrays.asList("Suman", "Kiran", "Amit");

        // Merging two lists, removing duplicates, and sorting
        List<String> mergedList = Stream.concat(list1.stream(), list2.stream())
                                        .distinct()
                                        .sorted()
                                        .collect(Collectors.toList());

        System.out.println("Merged and Sorted List: " + mergedList);
    }
}

Output

Merged and Sorted List: [Amit, Kiran, Priya, Raj, Suman]

Explanation

  • sorted(): Sorts the merged list alphabetically. You can also provide a custom comparator if needed.

Conclusion

Merging two lists in Java 8 is straightforward with the Stream API. By using methods like Stream.concat(), distinct(), and sorted(), you can efficiently merge lists, remove duplicates, and sort the final result. These tools provide a flexible and concise way to handle common list operations, making your code more readable and maintainable.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top