Java program to join two given lists in Java


The addAll() method of the java.util.ArrayList class is used to insert all of the elements in the specified collection into this list. To add contents of a list to another −

  • Create list1 by instantiating list objects (in this example we used ArrayList).

  • Add elements to it using add() method.

  • Create another list. Add elements to it.

  • Now add the elements of one list to other using the addAll() method.

Example

Live Demo

import java.util.ArrayList;
public class JoinTwoLists {
   public static void main(String args[]){
      ArrayList<String> list1 = new ArrayList<String>();
      list1.add("Apple");
      list1.add("Orange");
      list1.add("Banana");
      System.out.println("Contents of list1 ::"+list1);

      ArrayList<String> list2 = new ArrayList<String>();
      list2.add("Grapes");
      list2.add("Mango");
      list2.add("Strawberry");
      System.out.println("Contents of list2 ::"+list2);

      list1.addAll(list2);
      System.out.println("Contents of list1 after adding list2 to it ::"+list1);
   }
}

Output

Contents of list1 ::[Apple, Orange, Banana]
Contents of list2 ::[Grapes, Mango, Strawberry]
Contents of list1 after adding list2 to it ::[Apple, Orange, Banana, Grapes, Mango, Strawberry]

Updated on: 13-Mar-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements