Combine Two Lists in Java

Combine two lists in Java to create versatile data structures used for storing ordered collections of elements. This operation is crucial across various applications, from data processing to dynamic collection management. In this blog, we demonstrate different methods of combining two lists in Java, offering clear examples and highlighting each approach’s advantages to help efficiently manage and manipulate list data in your projects.

What is Java Lists?

The `List` interface in Java is part of the Java Collections Framework and represents an ordered collection of elements. It allows for positional access and insertion of elements, making it a powerful tool for managing dynamic arrays. Common implementations of the `List` interface include `ArrayList` and `LinkedList`.

Benefits of using lists in Java include:

1. Dynamic Sizing: Lists can grow and shrink in size dynamically, unlike arrays with fixed size.

2. Flexibility: Without using generics, lists can store heterogeneous elements, providing greater flexibility in handling data.

3. Built-in Methods: Lists come with a plethora of built-in methods like `add`, `remove`, `get`, `set`, and more, simplifying data manipulation tasks.

4. Iteration Support: You can easily iterate through lists using iterators or enhanced for-loops, which streamline code readability and maintainability.

Overall, lists are a versatile and essential component in Java, providing robust solutions for a wide range of data management needs.

Basic Method to Combine Two List in Java

The `addAll` method is a straightforward and widely used approach to combine two lists in Java. This method appends all elements from a specified collection to the end of the list that calls the method.

All list implementations like `ArrayList` and `LinkedList` inherit the `addAll` method from the `Collection` interface.

Code of Combine two list in Java using addAll method

Here’s a simple example demonstrating how to use the `addAll` method to combine two `ArrayList` objects:

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

public class CombineLists {
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<>();
        list1.add("A");
        list1.add("B");
        list1.add("C");

        List<String> list2 = new ArrayList<>();
        list2.add("D");
        list2.add("E");
        list2.add("F");

        list1.addAll(list2);

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

Explanation of the code:

Below Java code shows how to combine two list in java using the `addAll` method. 

  • It begins by importing necessary classes (`ArrayList` and `List`). In the `main` method, two `ArrayList` objects, `list1` and `list2`, are created and populated with elements (“A”, “B”, “C” for `list1` and “D”, “E”, “F” for `list2`). 
  • Then, `list1` calls the `addAll` method and passes `list2` as the argument. This appends all elements from `list2` to the end of `list1`. 
  • Finally, the combined list is printed to the console, resulting in `list1` containing all elements from both lists: `[A, B, C, D, E, F]`. 

This example displays a simple and effective way to merge two lists in Java.

Output:

Combined List: [A, B, C, D, E, F]

Combining Lists Using Java 8 Streams

Using `Stream.concat` Method- The `Stream.concat` method is used to concatenate two streams, resulting in a combined stream that includes all elements from the first stream followed by all elements from the second stream.

Code to Combine two list in Java using Stream.concat

The given example will demonstrate how to combine two lists using the `Stream.concat` method:

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

public class CombineListsWithStreams {
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<>();
        list1.add("A");
        list1.add("B");
        list1.add("C");

        List<String> list2 = new ArrayList<>();
        list2.add("D");
        list2.add("E");
        list2.add("F");

        // Combine lists using Stream.concat
        List<String> combinedList = Stream.concat(list1.stream(), list2.stream())
                                          .collect(Collectors.toList());

        System.out.println("Combined List: " + combinedList);
    }
}

Explanation of the code:

1. Two `ArrayList` objects, `list1` and `list2`, are created and populated with elements.

2. The `Stream.concat` method is used to concatenate the streams of `list1` and `list2`.

3. The concatenated stream is collected back into a list using `Collectors.toList()`.

4. The combined list is printed, resulting in a list containing all elements from both input lists.

Using `Stream.concat` is a modern and elegant way to combine lists in Java, leveraging the functional programming capabilities introduced in Java 8.

Output:

Combined List: [A, B, C, D, E, F]

Combining Lists Using Apache Commons Collections

A. Using ListUtils.union method

The `ListUtils.union` method combine two lists in java into a single list, removing duplicates while maintaining the order of elements.

Code to Combine two list in Java using ListUtils. Union method

 import org.apache.commons.collections4.ListUtils;
   import java.util.ArrayList;
   import java.util.List;

   public class CombineListsWithApacheCommons {
       public static void main(String[] args) {
           // Creating two lists
           List<String> list1 = new ArrayList<>();
           list1.add("A");
           list1.add("B");
           list1.add("C");

           List<String> list2 = new ArrayList<>();
           list2.add("B");
           list2.add("C");
           list2.add("D");

           // Combining lists using ListUtils.union
           List<String> combinedList = ListUtils.union(list1, list2);

           // Printing the combined list
           System.out.println("Combined List: " + combinedList);
       }
   }

Explanation of the code:

  • Finally, it prints the combined list, showing the result.
  • This code demonstrates how to combine two list in java using the `ListUtils.union` method from Apache Commons Collections. 
  • It creates two lists (`list1` and `list2`), each containing some elements. 
  • Then, it calls `ListUtils.union(list1, list2)` to combine the lists, resulting in a new list (`combinedList`) that contains all unique elements from both input lists. 

Output:

Combined List: [A, B, C, D]

Combining Lists Using Guava Library

Google developed Guava, an open-source Java library. It provides a rich set of utility classes and functions that complement the Java standard library, offering solutions for common programming challenges and enhancing productivity.

The Iterables.concat method in Guava concatenates multiple iterables into a single iterable. 

Code to combine two lists in Java using Iterables. concat

import com.google.common.collect.Iterables;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CombineListsWithGuava {
    public static void main(String[] args) {
        // Creating two lists
        List<String> list1 = new ArrayList<>(Arrays.asList("A", "B", "C"));
        List<String> list2 = new ArrayList<>(Arrays.asList("D", "E", "F"));

        // Combining lists using Iterables.concat
        Iterable<String> combinedIterable = Iterables.concat(list1, list2);

        // Printing the combined iterable
        System.out.print("Combined Iterable: ");
        for (String element : combinedIterable) {
            System.out.print(element + " ");
        }
    }
}

Explanation of the code-

  • This code demonstrates how to combine two list in java using the `Iterables.concat` method from Guava. 
  • It creates two lists (`list1` and `list2`) and then calls `Iterables.concat(list1, list2)` to combine them into a single iterable (`combinedIterable`). 
  • Finally, it iterates over the combined iterable and prints the elements, resulting in a sequence of elements from both input lists.

Output:

Combined Iterable: A B C D E F 

Combining lists in Java is essential for efficient programming, and this blog provides practical methods using various libraries.
We hope that our blog on ‘Combine two lists in Java’ Experimenting with these techniques enhances learning. For more programming resources, including Python, C, PHP, and HTML tutorials, visit Newtum. Engage in programming and continue your learning journey with user-friendly courses.

About The Author

Leave a Reply