Java program to merge two lists
https://www.theitroad.com
Here's a Java program to merge two lists using the addAll()
method of the ArrayList class:
import java.util.ArrayList; import java.util.List; public class MergeLists { public static void main(String[] args) { List<Integer> list1 = new ArrayList<Integer>(); List<Integer> list2 = new ArrayList<Integer>(); List<Integer> mergedList = new ArrayList<Integer>(); list1.add(1); list1.add(2); list1.add(3); list2.add(4); list2.add(5); list2.add(6); mergedList.addAll(list1); mergedList.addAll(list2); System.out.println("List 1: " + list1); System.out.println("List 2: " + list2); System.out.println("Merged list: " + mergedList); } }
In this program, we have created three ArrayList objects, list1
, list2
, and mergedList
. We have added some elements to list1
and list2
using the add()
method. We have then merged the two lists into mergedList
using the addAll()
method. Finally, we have printed out the three lists using the System.out.println()
method.