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:

Rest Web service: Filter và Interceptor với Jersey 2.x (P1)
Java Program to Generate a Random UnDirected Graph for a Given Number of Edges
How to Find an Element in a List with Java
Xây dựng ứng dụng Client-Server với Socket trong Java
Java Program to Implement Bucket Sort
Convert Hex to ASCII in Java
Inheritance and Composition (Is-a vs Has-a relationship) in Java
Java Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
Guide to the Java ArrayList
Giới thiệu Json Web Token (JWT)
Tránh lỗi NullPointerException trong Java như thế nào?
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Java Program to Implement String Matching Using Vectors
Custom JUnit 4 Test Runners
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
New Features in Java 12
Concurrent Test Execution in Spring 5
Xử lý ngoại lệ trong Java (Exception Handling)
Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
Guide to the Java TransferQueue
So sánh HashSet, LinkedHashSet và TreeSet trong Java
Java Program to Implement Warshall Algorithm
Java Program to subtract two large numbers using Linked Lists
Java Program to Represent Graph Using Adjacency Matrix
Java Program to Compute Discrete Fourier Transform Using Naive Approach
Java Program to Find Transitive Closure of a Graph
A Guide to BitSet in Java
A Guide to JUnit 5 Extensions
Enum trong java
Java Program to Implement Trie
Send an email with an attachment