Java - Merging two lists into a new list

Posted on October 23, 2016


In Java, List can be merged into a new list by using 

  • List.addAll() method
  • Stream (Introduced in Java8)

MergeTwoListExample.java

package com.boraji.tutorial;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author imssbora
 *
 */
public class MergeTwoListExample {
	public static void main(String[] args) {
		
		/*List 1*/
		List<String> list1=new ArrayList<>();
		list1.add("One");
		list1.add("Two");
		list1.add("Three");
		list1.add("Four");
		list1.add("Five");
		
		/*List 2*/
		List<String> list2=new ArrayList<>();
		list2.add("Six");
		list2.add("Seven");
		list2.add("Eight");
		list2.add("Nine");
		list2.add("Ten");
		
		/*Method 1 - Merging list1 and list2*/
		List<String> newList1=new ArrayList<>(list1);
		newList1.addAll(list2);
		System.out.println("Method 1 - Merged list="+newList1);
		
		/*Method 2 - Merging list1 and list2*/
		List<String> newList2=Stream.concat(list1.stream(), list2.stream()).collect(Collectors.toList());
		System.out.println("Method 2 - Merged list="+newList2);
		
	}
}

Output

Method 1 - Merged list=[One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten]
Method 2 - Merged list=[One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten]