Adding Multiple Items to ArrayList

Learn to add multiple items to an ArrayList in a single statement using simple to follow Java examples.

1. Arrays.asList() – Initializing with Multiple Items

To initialize an ArrayList with multiple items in a single line can be done by creating a List of items using Arrays.asList(), and passing the List to the ArrayList constructor.

In the given example, we are adding two strings “a” and “b” to the ArrayList.

ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("a", "b"));

2. Collections.addAll() – Add Multiple Items to Existing ArrayList

To add all items from another collection to this ArrayList, we can use Collections.addAll() method that adds all of the specified items to the given list. Note that the items to be added may be specified individually or as an array.

ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("a", "b"));

Collections.addAll(arrayList, "c", "d");

System.out.println(arrayList);   //[a, b, c, d]

Alternatively, we can use ArrayList constructor that accepts a collection and initializes the ArrayList with the items from the argument collection. This can be useful if we are adding the whole collection into this ArrayList.

List<String> namesList = Arrays.asList( "a", "b", "c");
ArrayList<String> instance = new ArrayList<>(namesList);

3. Stream API – Adding Selected Items to ArrayList

This method uses Java Stream API. We create a stream of elements from the first list, add a filter() to get the desired elements only, and then add the filtered elements to another list.

//List 1
List<String> namesList = Arrays.asList( "a", "b", "c");

//List 2
ArrayList<String> otherList = new ArrayList<>(Arrays.asList( "d", "e"));

//Do not add 'a' to the new list
    .filter(name -> !"a".equals(name))

System.out.println(otherList);   //[d, e, b, c]

In the above examples, we learned to all multiple elements to ArrayList. We have added all elements to ArrayList and then we saw the example to add only selected items to the ArrayList from the Java 8 stream API.

Happy Learning !!

Sourcecode Download

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “Adding Multiple Items to ArrayList”

  1. Add one value multiple to ArrayList of size n.

    import java.util.*;
    public class Program {
    	public static void main(String[] args) {
    		var result = new ArrayList<Integer>(Arrays.asList( new Integer[10] ));
                    Collections.fill(result, 10);
                    System.out.println( result );
    }	}

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.