Add Multiple Items to Java ArrayList
Learn to add multiple items to an ArrayList in a single statement using simple-to-follow Java examples.
1. Using List.of() or Arrays.asList() to Initialize a New ArrayList
To initialize an ArrayList with multiple items in a single line can be done by creating a List of items using either Arrays.asList() or List.of() methods. Both methods create an immutable List containing items passed to the factory method.
In the given example, we add two strings, “a” and “b”, to the ArrayList.
ArrayList arrayList = new ArrayList<>(Arrays.asList("a", "b")); //or ArrayList arrayList = new ArrayList<>(List.of("a", "b"));
2. Using Collections.addAll() to Add Items from an Existing ArrayList
To add all items from another collection to this ArrayList, we can use Collections.addAll() method that adds all of the specified items to the given list. Note that the items to be added may be specified individually or as an array.
ArrayList arrayList = new ArrayList<>(Arrays.asList("a", "b")); Collections.addAll(arrayList, "c", "d"); System.out.println(arrayList); //[a, b, c, d]
Alternatively, we can use ArrayList constructor that accepts a collection and initializes the ArrayList with the items from the argument collection. This can be useful if we add the whole collection into this ArrayList.
List namesList = Arrays.asList( "a", "b", "c"); ArrayList instance = new ArrayList<>(namesList);
3. Using Stream API to Add Only Selected Items
This method uses Java Stream API. We create a stream of elements from the first list, add a filter() to get the desired elements only, and then add the filtered elements to another list.
//List 1 List namesList = Arrays.asList( "a", "b", "c"); //List 2 ArrayList otherList = new ArrayList<>(Arrays.asList( "d", "e")); //Do not add 'a' to the new list namesList.stream() .filter(name -> !"a".equals(name)) .forEachOrdered(otherList::add); System.out.println(otherList); //[d, e, b, c]
In the above examples, we learned to add multiple elements to ArrayList. We have added all elements to ArrayList, and then we saw the example of adding only selected items to the ArrayList from the Java 8 stream API.
Add ArrayList to another ArrayList in Java | addAll method
A quick guide to add one ArrayList values into Another using ArrayList constructor and using addAll() method.
In this post, We will learn How to add ArrayList into a another ArrayList in java.
We can accumulate this in two ways.
1) While creating ArrayList object.
2) Using addAll method.
1) Adding existing ArrayList into new list:
ArrayList has a constructor which takes list as input. Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.
package com.adeepdrive.arraylist; import java.util.ArrayList; import java.util.List; // Java - W3schools public class AddAnotherList < public static void main(String[] args) < // Creating ArryList - Existing Object ListexistingList = new ArrayList(); existingList.add("America"); existingList.add("New York"); existingList.add("Sidny"); System.out.println("Existing ArrayList Object : " + existingList); // Creating a new ArrayList by passing exiting ArrayList List newList = new ArrayList(existingList); // Printng the new List System.out.println("Newly created ArrayList Object : " + newList); > >
Existing ArrayList Object : [America, New York, Sidny]
Newly created ArrayList Object : [America, New York, Sidny]
First created one ArrayList object as named existingList and added three values to them as America, New York, Sidny. Then printed values of existingList.
Next created another ArrayList object as newList by passing existing existingList and not added any values to it, just printed newList then we see the same values as existingList.
2. How to add using addAll method:
ArrayList has a method named addAll() which is very useful when we do not have access arraylist creation logic (creation implementation is in some jar — third party jar).
public boolean addAll(Collection c)
addAll Example program:
package com.adeepdrive.arraylist; import java.util.ArrayList; import java.util.List; // Java - W3schools public class AddAnotherListAddAll < public static void main(String[] args) < // getting
existing Roles. List existingRoles = getExistingRoles(); // We have new roles in the list. List newUserRoles = new ArrayList(); newUserRoles.add("TimesheetApprove"); newUserRoles.add("LeaveApprove"); newUserRoles.add("CabApprove"); // We have to add new roles to the existing roles then we should go for addAll // method. System.out.println("Printing roles before adding new roles: "+existingRoles); existingRoles.addAll(newUserRoles); System.out.println("Printing roles after adding new roles: "+existingRoles); > // For understanding, I have created new method in the same class. In real time, // this method will be in some jar which is provided by other application // managed by different team. public static List getExistingRoles() < // Creating ArryList - Existing Object ListexistingRoles = new ArrayList(); existingRoles.add("ReadOnly"); existingRoles.add("EmployeLevel"); existingRoles.add("MonitierLevel"); return existingRoles; > >
Printing roles before adding new roles: [ReadOnly, EmployeLevel, MonitierLevel]
Printing roles after adding new roles: [ReadOnly, EmployeLevel, MonitierLevel, TimesheetApprove, LeaveApprove, CabApprove]
Please see the comments given in the above program.
First got all existing roles by calling getExistingRoles method. Then, we have created another new ArrayList object then added new roles to it.
At this point we have two list and values as below.
existingRoles: [ReadOnly, EmployeLevel, MonitierLevel]
newUserRoles: [TimesheetApprove, LeaveApprove, CabApprove]
Next, we want to add newUserRoles to the existingRoles object.
Now observe before and after adding new roles in existingRoles.
Class ArrayList
Type Parameters: E - the type of elements in this list All Implemented Interfaces: Serializable , Cloneable , Iterable , Collection , List , RandomAccess Direct Known Subclasses: AttributeList , RoleList , RoleUnresolvedList
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.)
The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:
List list = Collections.synchronizedList(new ArrayList(. ));
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
This class is a member of the Java Collections Framework.
Java ArrayList.addAll() – Add Multiple Items to a List
The ArrayList.addAll(collection) appends all of the elements of argument Collection into the current List at the end. The order of appended elements is same as they are returned by the argument collection’s Iterator. To add a single item to the list, use add().
Please note that we can add elements of any type in ArrayList, but make the application code more predictable, we should add elements of a certain type only using generics for compile-time type safety.
The addAll() method first ensures that there is sufficient space in the list. If the list does not have space, then it grows the list by adding more spaces in the underlying array. Then addAll() appends new elements to the end of the list or at the specified index position.
public boolean addAll(Collection c); public boolean addAll(int fromIndex, Collection c);
- Method arguments – a Collection containing elements to be added to this list. when the fromIndex argument is present, the collection items are inserted at the specified index position.
- Method returns – true if this list changed as a result.
- Method throws – NullPointerException if the specified collection is null.
2. ArrayList.addAll() Example
We have the following list instances containing alphabets.
ArrayList list1 = new ArrayList<>(); //list 1 list1.add("A"); list1.add("B"); list1.add("C"); list1.add("D"); ArrayList list2 = new ArrayList<>(); //list 2 list2.add("E");
2.1. Appending Items to the End of List
The following Java program adds the elements of another list to the current arraylist using addAll(). We are declaring generic list types to ensure type safety in runtime.
list1.addAll(list2); System.out.println(list1); //combined list
2.2. Appending Items at the Specified Position
Let us pass the 'fromIndex' at which location the method will insert the elements from the specified collection. We are inserting the string “E” at the index position 2, i.e. into the middle of the current list.
list1.addAll(2, list2); System.out.println(list1); //combined list