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; import java.util.stream.Collectors; import java.util.stream.Stream; import com.google.common.collect.Lists; 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(list1.stream(), list2.stream()); final List<Integer> combined = stream.sorted().collect(Collectors.toList()); System.out.println(combined); // Just add all elements 2 second list or create // Third list final List<Integer> list3 = new ArrayList<Integer>(); list3.addAll(list1); list3.addAll(list3); // for sort, use collector Collections.sort(list3); System.out.println(list3); // For merging without duplicates and sorted final Set<Integer> uniq = new TreeSet<Integer>(); uniq.addAll(list1); uniq.addAll(list2); final List<Integer> uniqList = new ArrayList<>(uniq); System.out.println(uniqList); } }
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.