Close

Java - How to merge multiple Collections into a new one?

[Last Updated: May 21, 2018]

Java Collections Java 

Following example shows how to merge multiple collections to a new collection.

package com.logicbig.example;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class MergeCollections {
  public static <T, N extends Collection<T>> N mergeToNew(N newCollection,
                                                          Collection<T>... collectionsToMerge) {
      if (collectionsToMerge == null) {
          return newCollection;
      }
      for (Collection<T> ts : collectionsToMerge) {
          newCollection.addAll(ts);
      }
      return newCollection;
  }

  public static void main(String[] args) {
      List<Integer> l1 = List.of(1, 2, 3);
      List<Integer> l2 = List.of(20, 10, 5);
      Set<Integer> set = mergeToNew(new TreeSet<>(), l1, l2);
      System.out.println(set);
  }
}
[1, 2, 3, 5, 10, 20]

See Also