Add all the Elements of an ArrayList to another ArrayList
To add all the elements of an ArrayList to this ArrayList in Java, you can use ArrayList.addAll() method. Pass the ArrayList, you would like to add to this ArrayList, as argument to addAll() method.
Following is the syntax to append elements of ArrayList arraylist_2
to this ArrayList arraylist_1
.
</>
Copy
arraylist_1.addAll(arraylist_2)
addAll() returns a boolean value if the elements of other ArrayList are appended to this ArrayList.
Example 1 – Append Elements of an ArrayList to this ArrayList
In the following example, we shall take two ArrayLists, arraylist_1
and arraylist_2
, with elements in each of them. And then use addAll() method to append elements of arraylist_2
to arraylist_1
.
Java Program
</>
Copy
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> arraylist_1 = new ArrayList<String>();
arraylist_1.add("apple");
arraylist_1.add("banana");
ArrayList<String> arraylist_2 = new ArrayList<String>();
arraylist_2.add("mango");
arraylist_2.add("orange");
arraylist_1.addAll(arraylist_2);
arraylist_1.forEach(element -> {
System.out.println(element);
});
}
}
Output
apple
banana
mango
orange
Conclusion
In this Java Tutorial, we learned how to append elements of an ArrayList to another, using addAll() method.