How to join two ArrayLists in java

In this article we will learn how to combine two ArrayList in Java. We will be using the help of addAll() method of ArrayList class. Lets see how we can achieve it.

Joining Two ArrayList

Below are the steps we will be performing

  • Create two new arraylist arraylist al1 and al2.
  • Add elements to al1 and al2 using add() method.
  • Create a new ArrayList newList, use addAll() method add both al1 and al2 to newList.
public class JoinTwoArraListExample 
{
    public static void main(String args[])
    {
        ArrayList<String> al1 = new ArrayList<String>();
        ArrayList<String> al2 = new ArrayList<String>();
        
        //Adding elements to al1
        al1.add("one");
        al1.add("two");
        al1.add("three");
        //Adding elements to al2
        al2.add("four");
        al2.add("five");
        al2.add("six");
        
        //adding al1,al2 to newList
        ArrayList<String> newList = new ArrayList<String>();
        newList.addAll(al1);
        newList.addAll(al2);
        
        //Print the elements of newList
        System.out.println("**Combined List**");
        for(String val : newList)
        {
            System.out.println(val);
        }
    }
}

Output :

**Combined List**
one
two
three
four
five
six

Leave a Reply

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