Add Multiple Items to an Java ArrayList

1. Overview of ArrayList

In this quick tutorial, we’ll show to how to add multiple items to an already initialized ArrayList.

For an introduction to the use of the ArrayList, please refer to this article here.

2. AddAll

First of all, we’re going to introduce a simple way to add multiple items into an ArrayList.

First, we’ll be using addAll(), which takes a collection as its argument:

List<Integer> anotherList = Arrays.asList(5, 12, 9, 3, 15, 88);
list.addAll(anotherList);

It’s important to keep in mind that the elements added in the first list will reference the same objects as the elements in anotherList.

For that reason, every amends made in one of these elements will affect both lists.

3. Collections.addAll

The Collections class consists exclusively of static methods that operate on or return collections.

One of them is addAll, which needs a destination list and the items to be added may be specified individually or as an array.

Here it’s an example of how to use it with individual elements:

List<Integer> list = new ArrayList<>();
Collections.addAll(list, 1, 2, 3, 4, 5);

And another one to exemplify the operation with two arrays:

List<Integer> list = new ArrayList<>();
Integer[] otherList = new Integer[] {1, 2, 3, 4, 5};
Collections.addAll(list, otherList);

Similarly to the way explained in the above section, the contents of both lists here will refer to the same objects.

4. Using Java 8

This version of Java opens our possibilities by adding new tools. The one we’ll explore in the next examples is Stream:

List<Integer> source = ...;
List<Integer> target = ...;

source.stream().forEachOrdered(target::add);

The main advantages of this way are the opportunity to use skip and filters. In the next example we’re going to skip the first element:

source.stream()
  .skip(1)
  .forEachOrdered(target::add);

It’s possible to filter the elements by our necessities. For instance, the Integer value:

source.stream()
  .filter(i -> i > 10)
  .forEachOrdered(target::add);

Finally, there are scenarios where we want to work in a null-safe way. For those ones, we can use Optional:

Optional.ofNullable(source).ifPresent(target::addAll)

In the above example, we’re adding elements from source to target by the method addAll.

5. Conclusion

In this article, we’ve explored different ways to add multiple items to an already initialized ArrayList.

As always, code samples can be found over on GitHub.

Related posts:

HttpClient 4 – Send Custom Cookie
Hướng dẫn Java Design Pattern – Dependency Injection
Java Program to Implement Hamiltonian Cycle Algorithm
A Guide to LinkedHashMap in Java
Spring Boot - Servlet Filter
Implementing a Runnable vs Extending a Thread
ETL with Spring Cloud Data Flow
Java Program to Implement Hash Tables
Guide to the Volatile Keyword in Java
Finding Max/Min of a List or Collection
Sử dụng CountDownLatch trong Java
Converting a Stack Trace to a String in Java
Servlet 3 Async Support with Spring MVC and Spring Security
Guide to BufferedReader
Java Program to Implement Quick sort
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
Java Program to Implement Hash Tables Chaining with Doubly Linked Lists
Java Program to Implement Quick Sort with Given Complexity Constraint
Apache Commons Collections MapUtils
Extract network card address
Java Program to Find ith Largest Number from a Given List Using Order-Statistic Algorithm
Spring WebClient Requests with Parameters
Introduction to Spring Cloud CLI
Java Program to Generate All Possible Subsets with Exactly k Elements in Each Subset
Java Program to Check Whether an Undirected Graph Contains a Eulerian Path
Convert a Map to an Array, List or Set in Java
Java Program to Implement Miller Rabin Primality Test Algorithm
Spring MVC Setup with Kotlin
Java Program to Implement AA Tree
An Intro to Spring Cloud Security
Xây dựng ứng dụng Client-Server với Socket trong Java
So sánh HashSet, LinkedHashSet và TreeSet trong Java