How to Add Multiple Elements to List At Once in Java
I needed a way to add multiple elements to my ArrayList simultaneously.
How can we do that without a loop?
Using ArrayList.addAll()
We can add all items from another collection to an ArrayList using addAll()
.
List<String> lst = new ArrayList<>();
lst.addAll(Arrays.asList("corgi", "shih tzu", "pug"));
First, we would have to define a new list using Arrays.asList()
.
Then, we can call addAll()
on the original list.
Using Collections.addAll()
We can use the Collections
class, which contains many static methods to operate on collections.
Using addAll()
, we can add any number of elements into our collection.
List<String> lst = new ArrayList<>();
Collections.addAll(lst, "corgi", "shih tzu", "pug");
Using List.of()
As of Java 9, we can use List.of()
to instantiate an immutable list.
So, if this fits your use case, feel free to use this.
List<String> lst = List.of("corgi", "shih tzu", "pug");