Java Program to Add All Elements of List to ArrayList

In this article, we will learn how to add all the elements of List to ArrayList.

Java Program to Add All Elements of List to ArrayList

This can be done using an addAll() built-in method of the ArrayList class.

Syntax:

public boolean addAll(Collection c)

Parameter – ArrayList in which elements to be added

Let’s see the program to add all elements of list to ArrayList

Method: Java Program to Add All Elements of List to ArrayList By Using addAll() Method

Approach –

  1. Create a String ArrayList say basketArraylist and add elements into it using add() method.
  2. Create a String List say basketList and add elements into it.
  3. Then add all elements of the list to ArrayList using the addAll()
  4. Display the updated ArrayList.

 Program:

import java.util.ArrayList;
import java.util.List;

public class Main 
{

   public static void main(String a[])
   {

      // Declared Arraylist of String
      ArrayList<String> basketArraylist = new ArrayList<String>();

      //Adding elements to the ArrayList
      basketArraylist.add("Apple");
      basketArraylist.add("Mango");
      basketArraylist.add("Orange");

      System.out.println("ArrayList Elements are: "+ basketArraylist);

      //Adding elements to a List
      List<String> basketList = new ArrayList<String>();
      basketList.add("Tomato");
      basketList.add("Onion");
      basketList.add("Potato");

      //Adding all elements of list to ArrayList using addAll
      basketArraylist.addAll(basketList);

      // Updated ArrayList
      System.out.println("Updated ArrayList Elements are: "+ basketArraylist);
   }
}
Output:

ArrayList Elements are: [Apple, Mango, Orange]
Updated ArrayList Elements are: [Apple, Mango, Orange, Tomato, Onion, Potato]

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.