Append Collection elements to ArrayList : addAll(Collection c) method example

In this tutorial I will share how to use addAll(Collection c) method of java.util.ArrayList class. I have already share how to add element to the ArrayList and how to add element at specified position in the ArrayList. The syntax of the addAll method is :

public boolean addAll(Collection c)

According to Oracle docs,the add(Collection c) method appends all of the elements in the specified collection to the end of the list.

addAll(Collection c) method example


import java.util.*;
public class AddAllMethodExample {
    public static void main(String args[]) {
        // ArrayList1 of String type
        ArrayList<String> al = new ArrayList<String>();
        al.add("California");
        al.add("Illinois");
        al.add("New York");
        al.add("Texas");
        System.out.println("ArrayList1 before addAll:"+al);
        //ArrayList2 of String Type
        ArrayList<String> al2 = new ArrayList<String>();
        al2.add("Text1");
        al2.add("Text2");
        al2.add("Text3");
        al2.add("Text4");

        //Adding ArrayList2 into ArrayList1
        al.addAll(al2);
        System.out.println("ArrayList1 after addAll:"+al);


    }
}


Output


ArrayList1 before addAll:[California, Illinois, New York, Texas]
ArrayList1 after addAll:[California, Illinois, New York, Texas, Text1, Text2, Text3, Text4]




About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry