Add Multiple Elements to ArrayList in Java

In this short article, we will learn how to add multiple elements to an ArrayList in Java.

Add Multiple Elements to ArrayList in Java

The following example uses the addAll() method to add multiple elements to a list in one step.
import java.util.ArrayList;
import java.util.List;

public class AddingMultipleItemsEx {

    public static void main(String[] args) {

        List < String > colours1 = new ArrayList < > ();

        colours1.add("blue");
        colours1.add("red");
        colours1.add("green");

        List < String > colours2 = new ArrayList < > ();

        colours2.add("yellow");
        colours2.add("pink");
        colours2.add("brown");

        List < String > colours3 = new ArrayList < > ();
        colours3.add("white");
        colours3.add("orange");

        colours3.addAll(colours1);
        colours3.addAll(2, colours2);

        for (String col: colours3) {

            System.out.println(col);
        }
    }
}

Output

white
orange
yellow
pink
brown
blue
red
green
Two lists are created. Later, the elements of the lists are added to the third list with the addAll() method.
colours3.addAll(colours1);
The addAll() method adds all of the elements to the end of the list.
colours3.addAll(2, colours2);
This overloaded method adds all of the elements starting at the specified position.

Related Collections Examples

Comments