In this short article, we will learn how to add multiple elements to an ArrayList in Java.
Add Multiple Elements to ArrayList in Java
The following example uses the addAll() method to add multiple elements to a list in one step.
import java.util.ArrayList;
import java.util.List;
public class AddingMultipleItemsEx {
public static void main(String[] args) {
List < String > colours1 = new ArrayList < > ();
colours1.add("blue");
colours1.add("red");
colours1.add("green");
List < String > colours2 = new ArrayList < > ();
colours2.add("yellow");
colours2.add("pink");
colours2.add("brown");
List < String > colours3 = new ArrayList < > ();
colours3.add("white");
colours3.add("orange");
colours3.addAll(colours1);
colours3.addAll(2, colours2);
for (String col: colours3) {
System.out.println(col);
}
}
}
Output
white
orange
yellow
pink
brown
blue
red
green
Two lists are created. Later, the elements of the lists are added to the third list with the addAll() method.
colours3.addAll(colours1);
The addAll() method adds all of the elements to the end of the list.
colours3.addAll(2, colours2);
This overloaded method adds all of the elements starting at the specified position.
Related Collections Examples
- Java LinkedHashMap Example
- Java HashSet Example
- Java LinkedList Example
- Java ArrayList Example
- Java Comparator Interface Example
- Java Comparable Interface Example
- Java IdentityHashMap Example
- Java WeakHashMap Example
- Java EnumMap Example
- Java CopyOnWriteArraySet Example
- Java EnumSet Class Example
- Guide to Java 8 forEach Method
- Different Ways to Iterate over a List in Java [Snippet]
- Different Ways to Iterate over a Set in Java [Snippet]
- Different Ways to Iterate over a Map in Java [Snippet]
- Iterate over TreeSet in Java Example
- Iterate over LinkedHashSet in Java Example
- Remove First and Last Elements of LinkedList in Java
- Iterate over LinkedList using an Iterator in Java
- Search an Element in an ArrayList in Java
- Iterate over ArrayList using Iterator in Java
- Remove Element from HashSet in Java
- Iterating over a HashSet using Iterator
- How To Remove Duplicate Elements From ArrayList In Java?
- Different Ways to Iterate over List, Set, and Map in Java
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Comments
Post a Comment