Write a Java program to join two array lists


This is a Java program that joins two ArrayLists of Strings into a single ArrayList using the addAll method. Here's how the program works:

  • The program creates two ArrayLists of Strings, named list_str1 and list_str2, and initializes them with some values.
  • The program prints the contents of both ArrayLists using System.out.println.
  • The program creates a third ArrayList of Strings, named a, and initializes it to be an empty ArrayList.
  • The program uses the addAll method to add all the elements of list_str1 to a.
  • The program uses the addAll method again to add all the elements of list_str2 to a.
  • The program prints the contents of a using System.out.println.

Source Code

import java.util.ArrayList;
import java.util.Collections;
public class JoinTwo_Array
{
	public static void main(String[] args)
	{
		ArrayList<String> list_str1= new ArrayList<String>();
		list_str1.add("Laptop");
		list_str1.add("Keyboard");    
		list_str1.add("Mouse");
		list_str1.add("CPU");
		System.out.println("First Array list : " + list_str1);
		ArrayList<String> list_str2= new ArrayList<String>();
		list_str2.add("Printer");
		list_str2.add("Derive");
		list_str2.add("Monitor");
		System.out.println("Second Array List : " + list_str2);		
		ArrayList<String> a = new ArrayList<String>();
		a.addAll(list_str1);
		a.addAll(list_str2);
		System.out.println("Join Two Array List : " + a);
	}
}

Output

First Array list : [Laptop, Keyboard, Mouse, CPU]
Second Array List : [Printer, Derive, Monitor]
Join Two Array List : [Laptop, Keyboard, Mouse, CPU, Printer, Derive, Monitor]

Example Programs