Add all elements of a Collection to Java ArrayList Example

In this example we will learn how to add a entire collection to a  Java ArrayList. we will follow the below steps.

  • First step is that we need to create a new ArrayList.
  • Populate the ArrayList al1 with elements, using add(E e) API method of ArrayList.
  • Create a new ArrayList al2 and add elements to it using add(E e) method.
  • Using addAll(Collection c) we will add all the elements of al2 to al1

import java.util.ArrayList;

public class ArrayListAddAll 
{
	public static void main(String[] args) { 
        // Create ArrayList al1 object
        ArrayList al1 = new ArrayList();
        
        //adding elements to al1
        al1.add("String 1");
        al1.add("String 2");
        al1.add("String 3");
        al1.add("String 4");
        
        System.out.println("**Elements of al1 before adding**");
        for(String val: al1)
        {
        	System.out.println(val);
        }

        // Create ArrayList al2 object
        ArrayList al2 = new ArrayList();
        
        //adding elements to al2
        al2.add("Element 1");
        al2.add("Element 2");
        al2.add("Element 3");
        al2.add("Element 4");

        //Adding al2 to al1
        al1.addAll(al2);

        System.out.println("**Elements of al1 after adding**");
        for(String val: al1)
        {
        	System.out.println(val);
        }
   }
}

Output

**Elements of al1 before adding**
String 1
String 2
String 3
String 4
**Elements of al1 after adding**
String 1
String 2
String 3
String 4
Element 1
Element 2
Element 3
Element 4

Leave a Reply

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