Combine Two Lists in Java: addAll() Method

In Java, the method for merging two lists is using the addAll() method. Here is an example code:

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);

list1.addAll(list2);

System.out.println(list1);

The output is: [1, 2, 3, 4, 5, 6]

The code above first creates two lists, then uses the addAll() method to add the elements of list2 to list1, and finally prints the merged list1.

bannerAds