Java Program To Merge Two Lists
Chapter:
Miscellaneous
Last Updated:
17-05-2023 15:08:38 UTC
Program:
/* ............... START ............... */
import java.util.ArrayList;
import java.util.List;
public class MergeListsExample {
public static void main(String[] args) {
// Create two lists
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
list1.add(3);
List<Integer> list2 = new ArrayList<>();
list2.add(4);
list2.add(5);
list2.add(6);
// Merge the lists
List<Integer> mergedList = new ArrayList<>();
mergedList.addAll(list1);
mergedList.addAll(list2);
// Print the merged list
System.out.println("Merged list: " + mergedList);
}
}
/* ............... END ............... */
Output
Merged list: [1, 2, 3, 4, 5, 6]
Notes:
-
In this example, we create two lists called list1 and list2. list1 contains the numbers 1, 2, and 3, while list2 contains the numbers 4, 5, and 6.
- We then create a new list called mergedList, which will hold the merged result.
- To merge the lists, we use the addAll() method. We call mergedList.addAll(list1) to add all the elements of list1 to mergedList, and then we call mergedList.addAll(list2) to add all the elements of list2 to mergedList. This concatenates the elements from both lists into the mergedList.
- Finally, we print the merged list using System.out.println(), which displays the merged list as [1, 2, 3, 4, 5, 6].
- So, the program demonstrates how to merge two lists by using the addAll() method in Java.
Tags
Java Program To Merge Two Lists # How to Merge Two Lists in Java #Java merge two arrays