Add Multiple Elements to ArrayList in One Line

The Java ArrayList class is part of the Collection framework and is an implementation of a resizable array data structure. It automatically grows and shrinks when elements are added or removed in the runtime, whenever required,

This Java tutorial discussed the different ways to add multiple items to an ArrayList in a single statement using simple-to-follow Java examples.

1. Using List.of() or Arrays.asList() to initialize a new ArrayList

To initialize an ArrayList with multiple items in a single line can be done by creating a List of items using either Arrays.asList() or List.of() methods. Both methods create an immutable List containing items passed to the factory method.

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

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

//or

ArrayList<String> arrayList = new ArrayList<>(List.of("a", "b"));

2. Using Collections.addAll() to add Items from an 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 add the whole collection into this ArrayList.

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

3. Using Stream API to add only Selected Items

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
namesList.stream()
    .filter(name -> !"a".equals(name))
    .forEachOrdered(otherList::add);

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

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

Happy Learning !!

Sourcecode Download

Comments

Subscribe
Notify of
guest
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.