Java Program to Add Two ArrayList

In the previous article, we have seen Java Program to Get the Size of ArrayList

In this article we are going to see how we can add two arraylists in Java.

Java Program to Add Two ArrayList

In Java we have addAll() inbuilt method of java.util.ArrayList class which can be used to add all elements of one arraylist to another arraylist.

Let’s see the program to understand it more clearly.

Java Program to Add Two ArrayList by Using adAll() Method

Approach:

  • Create an arraylist and add some elements into it
  • Display the arraylist
  • Create another arraylist and add some elements into it.
  • Display the second arraylist
  • Pass the arraylists into addAll( ) to add the second arraylist to the first arraylist.
  • Print the new combined arrayList.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Creating an empty ArrayList
        ArrayList<String> arr1 = new ArrayList<String>();
        // Adding elements to the arrayList
        arr1.add("One");
        arr1.add("Two");
        arr1.add("Three");
        // Displaying the list
        System.out.println("Arraylist 1 "+arr1);

        ArrayList<String> arr2 = new ArrayList<String>();
        // Adding elements to the arrayList
        arr2.add("1");
        arr2.add("2");
        arr2.add("3");
        // Displaying the list
        System.out.println("Arraylist 2 "+arr2);

        // Combining both arraylists
        arr1.addAll(arr2);
        // Displaying the modified list
        System.out.println("New List "+arr1); 
    }
}

Output:

Arraylist 1 [One, Two, Three]
Arraylist 2 [1, 2, 3]
New List [One, Two, Three, 1, 2, 3]

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Related Java Programs: