java

How to Merge two ArrayLists in Java

In this tutorial, we are going to see different ways to concatenate two ArrayLists in Java.
 

Method 1: Using the List.addAll() method

The addAll() method is the easiest way to add all the elements of a given collection to the end of another list. Using this method, we can combine multiple lists into one list.

import java.util.*;
 
public class Main 
{
    public static void main(String[] args) throws Exception 
    {
        ArrayList<String> l1 = new ArrayList<>(Arrays.asList("1", "2", "3"));
        ArrayList<String> l2 = new ArrayList<>(Arrays.asList("4", "5", "6"));
        l1.addAll(l2); 
        System.out.println(l1);
    }
}

Output:

[1, 2, 3, 4, 5, 6]
 

Method 2: Using the Stream method

In the following code, we used the concat() method of “Stream” to concatenate two lists. Then we convert them back to List using toList().

import java.util.*;
import java.util.stream.*;

public class Main {

    public static void main(String[] args) {

        ArrayList<String> l1 = new ArrayList<>(Arrays.asList("1", "2", "3"));
        ArrayList<String> l2 = new ArrayList<>(Arrays.asList("4", "5", "6"));

        List<String> res =  Stream.concat(l1.stream(), l2.stream())
                .collect(Collectors.toList());

        System.out.println("List 1: " + l1);
        System.out.println("List 2: " + l2);
        System.out.println("Result: " + res);

    }
}

Output:

List 1: [1, 2, 3]
List 2: [4, 5, 6]
Result: [1, 2, 3, 4, 5, 6]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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