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.
