Either:

Set<Foo> fooSet = new LinkedHashSet<>(one);
fooSet.addAll(two);
List<Foo> finalFoo = new ArrayList<>(fooSet);

or

List<Foo> twoCopy = new ArrayList<>(two);
twoCopy.removeAll(one);
one.addAll(twoCopy);
Answer from Puce on Stack Overflow
🌐
Medium
medium.com › @AlexanderObregon › merging-two-arrays-into-one-without-duplicates-in-java-6931f8f9121e
Merging Two Arrays into One Without Duplicates in Java
August 7, 2025 - This makes it a good match when you want to combine values without repeated checks. HashSet is a common type of Set. It handles basic types like integers and strings by hashing them. The hash gives Java a quick way to store and look up values. When you use add, the item is turned into a hash value, and Java uses that hash to check whether the value has already been added. Here’s a simple way to merge two arrays using a set and avoid duplicates:
🌐
Techie Delight
techiedelight.com › home › java › merge two sets in java
Merge two sets in Java | Techie Delight
July 7, 2026 - This post will discuss how to merge two sets in Java using plain Java, Java 8, Guava, and Apache Commons Collections. Any duplicate element present in the set will be discarded during the merge.
🌐
Vultr Docs
docs.vultr.com › java › examples › calculate union of two sets
Java Program to Calculate union of two sets
December 19, 2024 - In this example, setA and setB are combined into union. The addAll() method ensures that all elements from both sets are added to union, and since it's a set, it automatically discards any duplicates.
🌐
GitHub
gist.github.com › 3e59f8bdca5050e6ec5c
Merging two arrayLists into a new arrayList, with no duplicates (Java) · GitHub
Merging two arrayLists into a new arrayList, with no duplicates (Java) - gist:3e59f8bdca5050e6ec5c
🌐
Techie Delight
techiedelight.com › home › java › merge multiple sets in java
Merge multiple sets in Java | Techie Delight
July 7, 2026 - In this post, several methods are discussed to merge multiple sets in Java into a single set using plain Java, Java 8, Guava, and Apache Commons. Please note that the merge operation will discard duplicate elements present in any set.
🌐
GeeksforGeeks
geeksforgeeks.org › java › merge-two-sets-in-java
Merge Two Sets in Java - GeeksforGeeks
July 11, 2025 - This interface contains the methods inherited from the Collection interface and adds a feature that restricts the insertion of the duplicate elements. There are two interfaces that extend the set implementation namely SortedSet and NavigableSet. Methods: Following are the various ways to merge two sets in Java:
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › merge-two-treesets-into-one-while-preserving-natural-order
How to Merge Two TreeSets into One while Preserving Natural Order? - GeeksforGeeks
July 23, 2025 - Print the resultant tree set. Below is the Program to Merge Two TreeSets into One while Preserving Natural Order: ... // Java program to merge two TreeSets // Into one while preserving natural order import java.util.TreeSet; // Driver Class public class GfGMergeTreeSets { // Main Function public static void main(String args[]) { // Create two TreeSets TreeSet<Integer> set1 = new TreeSet<>(); // Adding the elements into the set1 set1.add(5); set1.add(25); set1.add(15); TreeSet<Integer> set2 = new TreeSet<>(); // Adding the elements into the set1 set2.add(3); set2.add(8); set2.add(12); // Merge the two TreeSets TreeSet<Integer> mergedSet = new TreeSet<>(set1); mergedSet.addAll(set2); System.out.println("Merged TreeSet: " + mergedSet); } }
Top answer
1 of 3
1

I took a first try to shorten the iterator implementation while trying to keep it readeable. The difficulty I think comes in part in that with an iterator we actually consume elements, so you can not arbitrarily index elements. I came up with something like this:

public static List<Integer> mergeWithIterator(List<Integer> list1, List<Integer> list2) {
    List<Integer> sorted = new ArrayList<>();

    Iterator<Integer> iterator1 = list1.iterator();
    Iterator<Integer> iterator2 = list2.iterator();
    Integer element1 = null;
    Integer element2 = null;

    while (iterator1.hasNext() && iterator2.hasNext()) {
        if (element1 == null) {
            element1 = iterator1.next();
        }
        if (element2 == null) {
            element2 = iterator2.next();
        }
        if (element1 < element2) {
            sorted.add(element1);
            element1 = null;
        } else if (element1 > element2) {
            sorted.add(element2);
            element2 = null;
        } else {
            sorted.add(element1);
            element1 = null;
            element2 = null;
        }
    }

    if (element1 != null) {
        sorted.add(element1);
    }
    if (element2 != null) {
        sorted.add(element2);
    }

    while (iterator1.hasNext()) {
        sorted.add(iterator1.next());
    }
    while (iterator2.hasNext()) {
        sorted.add(iterator2.next());
    }

    return sorted;
}

This of course assumes null is an invalid element of your list (it would currently blow up anyway). You could even make some inline checks in order to remove the add remaining things after the loop, but I'd wager it will hinder the readeability. EDIT: tried it nonetheless:

public static List<Integer> mergeWithIterator(List<Integer> list1, List<Integer> list2) {
    List<Integer> sorted = new ArrayList<>();

    Iterator<Integer> iterator1 = list1.iterator();
    Iterator<Integer> iterator2 = list2.iterator();
    Integer element1 = iterator1.hasNext() ? iterator1.next() : null;
    Integer element2 = iterator2.hasNext() ? iterator2.next() : null;

    while (!(element1 == null && element2 == null)) {
        if (element2 == null || (element1 != null && element1 < element2)) {
            sorted.add(element1);
            element1 = iterator1.hasNext() ? iterator1.next() : null;
        } else if (element1 == null || (element2 != null && element2 < element1)) {
            sorted.add(element2);
            element2 = iterator2.hasNext() ? iterator2.next() : null;
        } else {
            sorted.add(element1);
            element1 = iterator1.hasNext() ? iterator1.next() : null;
            element2 = iterator2.hasNext() ? iterator2.next() : null;
        }
    }
    return sorted;
}

A simple (but possibly naive) streams implementation could be:

public static List<Integer> mergeWithStreams(List<Integer> list1, List<Integer> list2) {
    return Stream.concat(list1.stream(), list2.stream())
            .sorted()
            .distinct()
            .collect(toList());
}

As a sidenote, you you could make the methods more generic by defining the types of the elements as implementing the Comparable interface. This of course could invalidate the iterator implementation using null.

About performance, I think you should measure. For sufficiently large lists the iterator implementation might indeed get that extra bit of speed, as it's complexity is indeed linear w.r.t. the inputs.

For streaming and parallel, I do not think I have enough knowledge to answer that. My guess is that it would depend a lot on the format of the input, but in general would not be an improvement performance wise. Measure, measure, measure! It definitely is an improvement readeability wise though.

Maybe an other nice way would be to return an implementation of a list using given lists (or copies of them) as the backing collections. I'd imagine the implementation would be quite simple (depending on requirements).

2 of 3
0

Here's the neatest solution poor Java iterators allowed me:

import java.util.*;
import java.util.function.BiFunction;

public class SortedListMerger<T> {
    public static void main(String[] args) {
        Integer[] l1 = new Integer[] {1, 3, 5};
        Integer[] l2 = new Integer[] {1, 3, 4};
        SortedListMerger<Integer> m = new SortedListMerger<>((a, b)-> a * b, Comparator.comparingInt(a -> a));
        ArrayList<Integer> d = new ArrayList<>();
        m.merge(Arrays.asList(l1), Arrays.asList(l2), d);
        for (int i : d)
            System.out.println(i);
    }

    private BiFunction<T, T, T> ifEqual;
    private Comparator<T> cmp;

    public SortedListMerger(BiFunction<T, T, T> ifEqual, Comparator<T> cmp) {
        this.ifEqual = ifEqual;
        this.cmp = cmp;
    }

    public void merge(Iterable<T> src1, Iterable<T> src2, List<T> dest) {
        Iterator<T> src1i = src1.iterator();
        Iterator<T> src2i = src2.iterator();
        T elem1 = src1i.hasNext() ? src1i.next() : null;
        T elem2 = src2i.hasNext() ? src2i.next() : null;
        T prev = null;
        T curr;

        while (elem1 != null || elem2 != null) {
            if (elem1 != null && elem2 != null) {
                curr = cmp.compare(elem1, elem2) <= 0 ? elem1 : elem2;
                if (curr == elem1) {
                    elem1 = src1i.hasNext() ? src1i.next() : null;
                } else {
                    elem2 = src2i.hasNext() ? src2i.next() : null;
                }
            } else if (elem1 != null) {
                curr = elem1;
                elem1 = src1i.hasNext() ? src1i.next() : null;
            } else {
                curr = elem2;
                elem2 = src2i.hasNext() ? src2i.next() : null;
            }

            if (prev != null  &&  cmp.compare(prev, curr) == 0) {
                prev = ifEqual.apply(prev, curr);
            } else {
                dest.add(curr);
                prev = curr;
            }
        }
    }
}

the main method, merge, is only 30 lines

🌐
Java Tips
javatips.net › blog › join-two-list-in-java
Join Two List In Java & Remove Duplicates - Javatips.net
April 28, 2016 - import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.Set; public class MergeTwoListRemoveDuplicates { /** * Merge Two List & Remove Duplicate entries */ public static void main(String[] args) { ArrayList<String> list1 = new ArrayList<String>(); list1.add("Java"); list1.add("JSP"); list1.add("Servlet"); ArrayList<String> list2 = new ArrayList<String>(); list2.add("Spring"); list2.add("Hibernate"); list2.add("Java"); Set<String> list3 = new LinkedHashSet<String>(); list3.addAll(list1); list3.addAll(list2); System.out.println("List1 " + list1); System.out.println("List2 " + list2); System.out.println("List3 " + list3); } }
🌐
Medium
medium.com › @AlexanderObregon › javas-set-addall-method-explained-78ad24f2fead
Java's Set.addAll() Method Explained
December 12, 2024 - The addAll() method from the java.util.Set interface provides a great way to add all elements from a collection to an existing set. This method is particularly useful for merging datasets while preserving the unique characteristics of a set—no ...
🌐
Code4copy
code4copy.com › java › merge-list-java
Merge Two list in Java in Efficient Way – code4copy
August 29, 2020 - 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(Colle
🌐
Stack Overflow
stackoverflow.com › questions › 47490437 › how-do-i-merge-two-string-sets-in-java-but-only-if-they-have-common-elements
arraylist - How do I merge two string sets in Java but only if they have common elements? - Stack Overflow
public Set<String> mergeSetsIfAnyOverlap( Set<String> s1, Set<String> s2 ) { Set<String> s3 = new HashSet<String>( s1 ) ; // copy s3 s3.retainAll( s1 ) ; // keep only things in s3 (aka s1 ) that exist in s2 if( !s3.isEmpty() ) { // any common ...
🌐
amitph
amitph.com › home › java › how to merge multiple collections in java
How to Merge Multiple Collections in Java - amitph
November 22, 2024 - In this tutorial, we thoroughly understood how to merge multiple Java Collections to form a collection of combined elements. We covered plenty of examples using Java Streams, plain Java, Guava library, and Apache Commons Collections library. Lastly, we saw Java 8 streams way of concatenating collections without duplicate elements.
🌐
DigitalOcean
digitalocean.com › community › tutorials › merge-two-lists-in-java
How to Merge Two Lists in Java? | DigitalOcean
Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.