Create ArrayList from Another ArrayList in Java

This example demonstrates how to create anArrayList from anotherArrayList in Java.

Example 1: Create ArrayList from Another ArrayList in Java

To create a newArrayList from an existingArrayList in Java, you can use theArrayList constructor that accepts aCollection as a parameter. 

Here's an example:
import java.util.ArrayList;import java.util.List;public class ArrayListExample {    public static void main(String[] args) {        ArrayList<String> originalList = new ArrayList<>();        originalList.add("Element 1");        originalList.add("Element 2");        originalList.add("Element 3");        ArrayList<String> newList = new ArrayList<>(originalList);        // Print the elements of the new list        for (String element : newList) {            System.out.println(element);        }    }}

In the code above, we create an originalListArrayList and add some elements to it. Then, we create a new ArrayListnewList by passingoriginalList as a parameter to the ArrayList constructor. This constructor initializes the newArrayList with the elements of the originalList.

Finally, we iterate over the elements of thenewList and print them.

Output:

Element 1Element 2Element 3

By using this approach, you can create a newArrayList with the same elements as the original one. Note that the elements themselves are not copied, only references to them are stored in the newArrayList. If you modify the elements in the originalList or newList, the changes will be reflected in both lists since they reference the same objects.

Example 2: Create ArrayList from Another ArrayList in Java

This example 2 demonstrates the following operations:
  • Create anArrayList from another collection using theArrayList(Collection c) constructor.
  • Adding all the elements from an existing collection to the newArrayList using theaddAll() method.
importjava.util.ArrayList;importjava.util.List;publicclassCreateArrayListFromCollectionExample {publicstaticvoidmain(String[]args) {List<Integer> firstFivePrimeNumbers=newArrayList<>();        firstFivePrimeNumbers.add(2);        firstFivePrimeNumbers.add(3);        firstFivePrimeNumbers.add(5);        firstFivePrimeNumbers.add(7);        firstFivePrimeNumbers.add(11);// Creating an ArrayList from another collectionList<Integer> firstTenPrimeNumbers=newArrayList<>(firstFivePrimeNumbers);List<Integer> nextFivePrimeNumbers=newArrayList<>();        nextFivePrimeNumbers.add(13);        nextFivePrimeNumbers.add(17);        nextFivePrimeNumbers.add(19);        nextFivePrimeNumbers.add(23);        nextFivePrimeNumbers.add(29);// Adding an entire collection to an ArrayList        firstTenPrimeNumbers.addAll(nextFivePrimeNumbers);System.out.println(firstTenPrimeNumbers);    }}

Output

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Reference


Java ArrayList Source Code Examples


Comments