List.addAll()
Adds all elements of another collection to a list.
Available since: Java 1.2
Syntax
boolean addAll(Collection<? extends E> c)
boolean addAll(int index, Collection<? extends E> c)Parameters
| Parameter | Type | Description |
|---|---|---|
| index | int | Optional position where the elements are inserted. |
| c | Collection<? extends E> | The collection of elements to add. |
Return value
boolean`true` if the list changed.
Examples
Joining two lists:
void main() {
List<Integer> all = new ArrayList<>(List.of(1, 2));
all.addAll(List.of(3, 4));
all.addAll(0, List.of(-1, 0));
IO.println(all);
}Output:
[-1, 0, 1, 2, 3, 4]Notes
The method is declared in Collection, so it works on sets too, where it adds only missing elements. Do not add a list to itself (list.addAll(list)) — the result is undefined.
See also
- List.add() — Adds an element to the end of a list or at a given position.
- Set.addAll() — Merges a set with another collection (union).
- Collections.sort() — Sorts a list in place.
Related recipes
In the tutorial
- Lists: List and ArrayList — Lists in Java: ArrayList, adding, reading and removing elements, unmodifiable List.of lists and lists of numbers.