How to Find Union of Two Sets in Java - Simple Guide
To find the union of two sets in Java, use the
addAll() method of the Set interface. This method adds all elements from one set into another, combining them without duplicates.Syntax
The union of two sets can be found using the addAll() method. Here is the syntax:
set1.addAll(set2);- Adds all elements ofset2intoset1.
This modifies set1 to contain all unique elements from both sets.
java
Set<Type> set1 = new HashSet<>(); Set<Type> set2 = new HashSet<>(); set1.addAll(set2);
Example
This example shows how to create two sets of strings and find their union using addAll(). The result is printed to the console.
java
import java.util.HashSet; import java.util.Set; public class UnionExample { public static void main(String[] args) { Set<String> set1 = new HashSet<>(); set1.add("apple"); set1.add("banana"); Set<String> set2 = new HashSet<>(); set2.add("banana"); set2.add("cherry"); set1.addAll(set2); // union of set1 and set2 System.out.println("Union of sets: " + set1); } }
Output
Union of sets: [banana, cherry, apple]
Common Pitfalls
One common mistake is modifying the original sets unintentionally. addAll() changes the set it is called on. To keep original sets unchanged, create a new set first.
Another pitfall is using lists instead of sets, which allow duplicates and do not have addAll() behave like a union.
java
import java.util.HashSet; import java.util.Set; public class UnionPitfall { public static void main(String[] args) { Set<String> set1 = new HashSet<>(); set1.add("apple"); Set<String> set2 = new HashSet<>(); set2.add("banana"); // Wrong: modifies set1 directly set1.addAll(set2); // Right: create new set to keep originals unchanged Set<String> union = new HashSet<>(set1); union.addAll(set2); System.out.println("Modified set1: " + set1); System.out.println("Union without modifying originals: " + union); } }
Output
Modified set1: [apple, banana]
Union without modifying originals: [apple, banana, banana]
Quick Reference
- addAll(): Adds all elements from another set to this set.
- HashSet: Common implementation of Set interface.
- Creating new set: Use
new HashSet<>(existingSet)to avoid modifying original sets.
Key Takeaways
Use
addAll() method to find the union of two sets in Java.Calling
addAll() modifies the set it is called on, so create a new set to keep originals unchanged.Sets automatically avoid duplicates, so union contains unique elements only.
Use
HashSet for efficient set operations.Avoid using lists for union if you want unique elements.