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?
We can add all items from another collection to an ArrayList using
List<String> lst = new ArrayList<>(); lst.addAll(Arrays.asList("corgi", "shih tzu", "pug"));
First, we would have to define a new list using
Then, we can call
addAll() on the original list.
We can use the
Collections class, which contains many static methods to operate on collections.
addAll(), we can add any number of elements into our collection.
List<String> lst = new ArrayList<>(); Collections.addAll(lst, "corgi", "shih tzu", "pug");
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");