Java Program to Concatenate Two List


Introduction

In Java, a list is an ordered collection of elements that allows duplicates. Sometimes, we may need to combine two lists into one list. Concatenating two lists means joining the elements of the two lists to form a new list containing all the elements of both lists. There are various ways to concatenate two lists in Java, including using loops, streams, and built-in methods. In this context, we will explore different approaches to concatenate two lists in Java.

One approach is to use the addAll() method provided by the List interface. This method adds all the elements of one list to another list. Another approach is to use the Stream API provided by Java 8 to concatenate two lists using flatMap() and collect() methods.

Yet another approach is to use a HashSet to remove duplicates from the first list and then add all the elements of the second list to it. Finally, we can convert the concatenated elements back to a List using the ArrayList constructor that takes a Collection as an argument.

Methods

There are Several Methods to Perform Concatenation Operation

  • Using addAll() method

  • Using stream

  • Using union()

Method 1: Using addAll()

addAll() is a method in Java that adds all elements of a collection to another collection.

Approach

  • First, two ArrayLists (list1 and list2) are created and initialized with some string elements.

  • Then, a new ArrayList concatenatedList is created with the same elements as list1 by passing list1 as an argument to the ArrayList constructor.

  • The addAll() method is used to add all the elements of list2 to the end of concatenatedList. This results in the concatenation of list1 and list2.

  • Finally, the concatenated list is printed to the console using the System.out.println() method.

Example

Here's an example Java program that concatenates two lists using the addAll() method −

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

public class ConcatenateLists {
   public static void main(String[] args) {
      // Create the first list
      List<String> list1 = new ArrayList<>();
      list1.add("apple");
      list1.add("banana");
      list1.add("orange");

      // Create the second list
      List<String> list2 = new ArrayList<>();
      list2.add("grape");
      list2.add("kiwi");
      list2.add("melon");

      // Concatenate the two lists
      List<String> concatenatedList = new ArrayList<>(list1);
      concatenatedList.addAll(list2);

      // Print the concatenated list
      System.out.println("Concatenated list: " + concatenatedList);
   }
}

Explanation

This program creates two lists of strings (list1 and list2), and then uses the addAll() method to concatenate them into a new list (concatenatedList). The addAll() method adds all of the elements from list2 to the end of concatenatedList. Note that we pass list1 to the ArrayList constructor to create a new list with the same elements as list1. This ensures that the order of the elements in list1 is preserved in the concatenated list.

Output

Concatenated list: [apple, banana, orange, grape, kiwi, melon]

Method 2: Using Stream

Stream is a Java API that allows functional-style operations on collections, providing parallel processing and lazy evaluation.

Approach

  • First, two ArrayLists (list1 and list2) are created and initialized with some string elements.

  • The concat() method of the Stream interface is used to concatenate the two lists. This method takes two streams as input and returns a new stream that contains all the elements of the input streams.

  • In order to use the concat() method, we need to convert the two lists into streams using the stream() method. Here, we are using list1.stream() and list2.stream() to convert list1 and list2 into streams.

  • The resulting stream is then collected into a list using the collect() method of the Collectors class. The toList() method of the Collectors class is used to collect the elements of the stream into a new List.

  • Finally, the concatenated list is printed to the console using the System.out.println() method.

Example

Here's an example Java program that concatenates two lists using streams −

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

public class ConcatenateListsUsingStream {
   public static void main(String[] args) {
      // Create the first list
      List<String> list1 = new ArrayList<>();
      list1.add("apple");
      list1.add("banana");
      list1.add("orange");

      // Create the second list
      List<String> list2 = new ArrayList<>();
      list2.add("grape");
      list2.add("kiwi");
      list2.add("melon");

      // Concatenate the two lists using streams
      List<String> concatenatedList = Stream.concat(list1.stream(), list2.stream())
      .collect(Collectors.toList());

      // Print the concatenated list
      System.out.println("Concatenated list: " + concatenatedList);
   }
}

Explanation

This program uses the concat() method of the Stream interface to concatenate the two lists. The concat() method takes two streams as input and returns a new stream that contains all the elements of the input streams. The resulting stream is then collected into a list using the collect() method of the Collectors class.

Note that in order to use streams, we need to import the Stream and Collectors classes.

This approach has the advantage of being more concise than the previous approach, but it may not be as efficient for large lists because it creates a new stream and a new list to hold the concatenated elements.

Output

Concatenated list: [apple, banana, orange, grape, kiwi, melon]

Method 3: Using Union()

union() is a method in Java that returns the union of two sets, containing all distinct elements from both sets.

Approach

  • Two ArrayLists (list1 and list2) are created and initialized with some string elements.

  • A HashSet is created from list1 using its constructor, which takes a Collection as an argument. This automatically removes any duplicates from list1 and stores the unique elements in the HashSet.

  • The addAll() method of the HashSet is used to add all the elements of list2 to the set. This also ensures that any duplicates in list2 are automatically removed.

  • The concatenated elements are then converted back to an ArrayList using the ArrayList constructor that takes a Collection as an argument. This constructor creates a new ArrayList with the same order as the original set.

  • Finally, the concatenated list is printed to the console using the System.out.println() method.

Example

Here's an example Java program that concatenates two lists using the union() method of the Set interface −

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ConcatenateListsUsingUnion {
   public static void main(String[] args) {
      // Create the first list
      List<String> list1 = new ArrayList<>();
      list1.add("apple");
      list1.add("banana");
      list1.add("orange");

      // Create the second list
      List<String> list2 = new ArrayList<>();
      list2.add("grape");
      list2.add("kiwi");
      list2.add("melon");

      // Concatenate the two lists using the union() method
      Set<String> set = new HashSet<>(list1);
      set.addAll(list2);
      List<String> concatenatedList = new ArrayList<>(set);

      // Print the concatenated list
      System.out.println("Concatenated list: " + concatenatedList);
   }
}

Explanation

  • This program uses the union() method to concatenate the two lists. The union() method takes two sets as input and returns a new set that contains all the elements of the input sets.

  • Here, we are using a HashSet to create a set from list1 and then adding all the elements of list2 to the set using the addAll() method. Finally, the concatenated elements are converted back to an ArrayList using the ArrayList constructor that takes a Collection as an argument.

  • Note that the use of a Set guarantees that there will be no duplicates in the resulting list.

  • This approach has the advantage of being simple and efficient, as Set operations have a time complexity of O(1) on average. However, it may not preserve the order of the elements in the original lists.

Output

Concatenated list: [banana, orange, apple, kiwi, grape, melon]

Conclusion

  • Concatenating two lists in Java is a common task in programming, and there are several approaches to achieve this. The choice of approach depends on various factors, including the size of the lists, the need to remove duplicates, and the desired performance and memory requirements.

  • In this context, we explored three different approaches to concatenate two lists in Java. We used the addAll() method provided by the List interface, the Stream API provided by Java 8, and a HashSet to remove duplicates from the first list and then add all the elements of the second list to it. Finally, we converted the concatenated elements back to a List using the ArrayList constructor that takes a Collection as an argument.

Updated on: 10-Apr-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements