Merge Two list in Java in Efficient Way

While doing development many times we need to merge two or more collections in Java. Sometimes we need simple concatenate two or more lists or sets or merge two or more lists by removing duplicates and sometimes we need to do this is sorted order.

Here is one example to merge two lists, this can be extended to merge 2 or more lists.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;


public class MergeTwoListSorted {

	public static void main(final String[] args) {
		final List<Integer> list1 = Lists.newArrayList(10, 20, 3, 4);
		final List<Integer> list2 = Lists.newArrayList(44, 10, 20, 3, 4);

		// Using stream
		final Stream<Integer> stream = Stream.concat(,;
		final List<Integer> combined = stream.sorted().collect(Collectors.toList());

		// Just add all elements 2 second list or create
		// Third list
		final List<Integer> list3 = new ArrayList<Integer>();

		// for sort, use collector

		// For merging without duplicates and sorted

		final Set<Integer> uniq = new TreeSet<Integer>();

		final List<Integer> uniqList = new ArrayList<>(uniq);


In the above example first Java 8 stream API has been used to merge two lists in sorted order. If you do not want to sort the just do not call .sorted() method of the stream.

Second is straight forward just add all lists to one new or existing list and if required call Collections.sort method.

The third one is most efficient when you want to merge lists in sorted order without duplicates. TreeSet maintains sorted and unique values naturally.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.