In this tutorial, you will learn how to add multiple items to an ArrayList in Java.
1. Add multiple items using adAll() method
The addAll() can be used to add multiple items to an ArrayList. This method takes another list as an argument and add the elements of the passed list to the ArrayList.
Here, we have a list that contains multiple items, we are adding these multiple items to the newly created ArrayList using addAll()
method as shown below.
import java.util.*; public class JavaExample { public static void main(String[] args) { List<String> list = Arrays.asList("hi", "hello", "bye"); ArrayList<String> al = new ArrayList<String>(); al.addAll(list); System.out.println("Original List elements:"+list); System.out.println("ArrayList elements:"+al); //Adding element to the arraylist al.add("hey"); System.out.println("Original List elements:"+list); System.out.println("ArrayList elements:"+al); } }
Output:
Original List elements:[hi, hello, bye] ArrayList elements:[hi, hello, bye] Original List elements:[hi, hello, bye] ArrayList elements:[hi, hello, bye, hey]
2. Add multiple items using Collections.adAll() method
The another way of adding multiple items to an ArrayList is using the Collections.addAll()
method. This method takes two argument. The first argument is the collection where the elements needs to be added and the second argument is the collection from where the items are copied.
For example: The following statement will add the specified elements to the list
.
Collections.addAll(list, "Item1", "Item2",);
Let’s take a look at the complete example:
Here, we have created an ArrayList list
. We are adding multiple elements to it using Collections.addAll()
method by passing list as the first argument and items as the second argument.
import java.util.*; public class JavaExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); Collections.addAll(list, "Mango","Apple", "Banana"); System.out.println("ArrayList elements:"+list); } }
Output:
ArrayList elements:[Mango, Apple, Banana]
Recommended Articles: