Java Set Union: A Step-by-Step Guide
In this article
To perform a union of two sets in Java, you combine all elements from both sets into a single set that contains no duplicates. The result is a new set that includes every unique element from both input sets. The most common way to do this is to create a new set, add all elements from the first set, then add all elements from the second set—since sets automatically reject duplicates, the union is formed. Alternatively, you can use the addAll() method on a copy of one set, or use the Stream API with Stream.concat() and Collectors.toSet(). This guide walks you through each approach, explains common pitfalls, and helps you troubleshoot when things don't go as planned.
What You'll Need
- A Java development environment (JDK 8 or later recommended for Stream API examples).
- Basic familiarity with Java collections, especially the
Setinterface and its common implementations likeHashSetandTreeSet. - Two sets containing elements of the same type (or compatible types) that you want to combine.
Step-by-Step
- Choose your set implementations. Decide which concrete
Setclasses you will use.HashSetis the most common choice for general-purpose sets because it offers constant-time performance for basic operations, assuming the hash function disperses elements properly.LinkedHashSetpreserves insertion order, andTreeSetkeeps elements sorted. For a union, anySetimplementation works, but the result will inherit the characteristics of the set you add into. - Create and populate your two sets. For example:
Note that "banana" appears in both sets; the union should contain it only once.Set<String> setA = new HashSet<>(Arrays.asList("apple", "banana", "cherry")); Set<String> setB = new HashSet<>(Arrays.asList("banana", "date", "elderberry")); - Create a new set to hold the union. It's good practice to avoid modifying the original sets. You can instantiate a new set with the same generic type:
If you want to preserve the iteration order of one of the sets, useSet<String> union = new HashSet<>();LinkedHashSetinstead. If you want sorted order, useTreeSet. - Add all elements from the first set. Use the
addAll()method:
This copies every element fromunion.addAll(setA);setAintounion. Sinceunionis a set, duplicates withinsetA(if any) are automatically eliminated, but sets by definition have no duplicates anyway. - Add all elements from the second set. Again, use
addAll():
Nowunion.addAll(setB);unioncontains all unique elements from both sets. Any element that was already present (like "banana") is not added again. - Verify the result. Print or inspect the union set to confirm it contains the expected elements. For the example above, the union should contain "apple", "banana", "cherry", "date", and "elderberry". The order depends on the set implementation:
HashSetdoes not guarantee order,LinkedHashSetpreserves insertion order (first set then second set, with duplicates skipped), andTreeSetsorts elements naturally. - Consider using the Stream API (optional). If you prefer a functional style, you can achieve the union with streams:
This creates a new set containing all elements from both streams. Note thatSet<String> union = Stream.concat(setA.stream(), setB.stream()) .collect(Collectors.toSet());Collectors.toSet()returns aHashSetby default, so order is not preserved. If you need a specific set implementation, useCollectors.toCollection(LinkedHashSet::new)or similar. - Use the union in your code. Once you have the union set, you can iterate over it, check for membership, or pass it to other methods. Remember that the union is a new set; the original sets remain unchanged.
Common Mistakes
- Modifying the original sets unintentionally. If you call
setA.addAll(setB)instead of creating a new set, you mutatesetA. This can lead to unexpected side effects if other parts of your code rely onsetAremaining unchanged. Always create a new set for the union unless you explicitly want to modify one of the inputs. - Assuming order is preserved with HashSet.
HashSetdoes not guarantee any iteration order. If you need the union to maintain the order of elements as they appeared in the original sets, useLinkedHashSet. If you need sorted order, useTreeSet. - Forgetting that sets require proper
equals()andhashCode()implementations. If you are storing custom objects in your sets, the union operation relies on these methods to detect duplicates. If they are not correctly implemented, duplicate objects may appear in the union or elements may be lost. - Using the wrong generic types. The two sets must have compatible element types. For example, you cannot directly union a
Set<Integer>with aSet<String>without casting or converting, which would likely be a design error. - Null elements. Some set implementations (like
TreeSet) do not permit null elements, whileHashSetandLinkedHashSetdo. If your sets contain nulls and you use aTreeSetfor the union, you'll get aNullPointerException. Check for nulls or choose an appropriate implementation.
Tips
- If you need to perform many unions, consider writing a utility method that takes two sets and returns a new set, encapsulating the logic and reducing code duplication.
- For large sets, the
addAll()approach is generally efficient: it iterates over the smaller set and adds each element to the larger set, with constant-time performance per addition forHashSet. The Stream API approach may create intermediate objects, so preferaddAll()for performance-critical code. - When using
TreeSetfor the union, ensure that the elements are mutually comparable (implementComparable) or provide aComparatorto theTreeSetconstructor. Otherwise, you'll get aClassCastExceptionat runtime. - Remember that the union of two sets is commutative: the order in which you add the sets does not affect the final set of elements (though it may affect iteration order in ordered sets).
- If you only need to check whether one set is a subset of another or perform other set operations, Java's
Setinterface provides methods likecontainsAll(),retainAll(), andremoveAll()that can be useful in combination with union.
Troubleshooting
- Union contains unexpected duplicates. This usually means the elements'
equals()andhashCode()methods are not consistent or not overridden correctly. For custom classes, ensure both methods are implemented based on the same fields. Also, check that you are not using a set implementation that allows duplicates (all standardSetimplementations disallow duplicates, but aListmisused as a set would not). - NullPointerException when adding to a TreeSet.
TreeSetdoes not allow null elements. If either set contains null, the union operation will throw aNullPointerException. Remove nulls before the union or use aHashSetorLinkedHashSetinstead. - ClassCastException when using TreeSet. If the elements are not mutually comparable,
TreeSetwill throw aClassCastExceptionwhen you add the second set. Ensure all elements implementComparableor provide aComparatorthat can compare any two elements. - Union set is empty or missing elements. Check that you actually populated the original sets and that you are adding them in the correct order. Also, verify that the
addAll()calls are on the union set, not on one of the originals. If using streams, ensure the stream pipeline is correct and thatcollectis called. - Performance issues with large sets. If the union operation is slow, consider the set implementations.
HashSetis generally fastest for add and contains operations. Avoid usingTreeSetfor very large sets if sorting is not required, as add operations are O(log n). Also, pre-size the union set if you know the approximate size to reduce rehashing:new HashSet<>(setA.size() + setB.size()).
Frequently Asked Questions
Can I perform a union of two sets without creating a new set?
Yes, you can modify one of the existing sets by calling setA.addAll(setB). This will add all elements from setB into setA, effectively making setA the union. However, this mutates setA, so use this approach only if you no longer need the original setA unchanged.
What is the difference between union and intersection of sets?
Union combines all unique elements from both sets, while intersection contains only elements that are present in both sets. In Java, you can compute the intersection by creating a new set and calling retainAll() with the other set.
Does the order of elements matter in a union?
For sets, order is not inherently meaningful because sets are unordered collections (except for LinkedHashSet and TreeSet, which have predictable iteration order). The union operation itself does not depend on order; the resulting set's iteration order depends on the implementation you choose.
Can I union sets of different types?
No, the elements must be of compatible types. You cannot directly union a Set<Integer> with a Set<String> because the resulting set would need a common supertype, and the operation would not make sense without conversion. You could union sets of a common supertype, such as Set<Number> containing both integers and doubles.
How do I union multiple sets at once?
You can chain addAll() calls: create a new set, then call addAll() for each set you want to include. Alternatively, use the Stream API: Stream.of(set1, set2, set3).flatMap(Set::stream).collect(Collectors.toSet()).
Is the union operation thread-safe?
No, standard Set implementations like HashSet are not thread-safe. If multiple threads access or modify the sets concurrently, you must synchronize access externally or use a thread-safe set implementation like ConcurrentHashMap.newKeySet() or Collections.synchronizedSet().