1.

Write a program in java to join two arraylists into one arraylist.

Answer»

We use the addAll() METHOD of the ArrayList class to add the contents of both the given arraylists into a new arraylist.

//importing the required header filesimport JAVA.util.ArrayList;import java.util.Collections; public class Join_Lists { public static void main(STRING[] args) { //creating the first array list ArrayList<String> list_1 = new ArrayList<String>(); list_1.add("Monday"); list_1.add("TUESDAY"); list_1.add("Wednesday"); list_1.add("Thursday"); //printing the first array list System.out.println("The elements of the first array list is as follows : " + list_1); //creating the second array list ArrayList<String> list_2 = new ArrayList<String>(); list_2.add("Friday"); list_2.add("Saturday"); list_2.add("Sunday"); //printing the second array list System.out.println("The elements of the second array list is as follows : " + list_2); //creating the third array list ArrayList<String> joined_list = new ArrayList<String>(); joined_list.addAll(list_1);//adding the elements of the first array list joined_list.addAll(list_2);//adding the elements of the second array list System.out.println("The elements of the joined array list is as follows : " + joined_list); }}

Output:

The elements of the first array list is as follows : [Monday, Tuesday, Wednesday, Thursday]The elements of the second array list is as follows : [Friday, Saturday, Sunday]The elements of the joined array list is as follows : [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]Useful Resources:

Basics of Java

Java Developer Skills

Online Java Compiler

Java MCQ



Discussion

No Comment Found