🔄 Let’s implement the symmetric difference of two collections in Java using only standard Collection
methods like addAll()
, removeAll()
, and retainAll()
— no custom loops, no streams, just pure Java Collections API.
✅ What is symmetric difference?
The symmetric difference between two sets A
and B
is the set of elements that are in either A or B, but not in both:
A △ B = (A ∪ B) - (A ∩ B)
Or in Java terms:
(A + B) - (A.retainAll(B))
💡 Java Implementation:
import java.util.*;
public class SymmetricDifferenceExample {
public static void main(String[] args) {
Collection<String> setA = new ArrayList<>(List.of("apple", "banana", "cherry"));
Collection<String> setB = new ArrayList<>(List.of("banana", "date", "cherry"));
// Step 1: Union of A and B
Collection<String> result = new ArrayList<>(setA);
result.addAll(setB); // result = A ∪ B
// Step 2: Intersection of A and B
Collection<String> intersection = new ArrayList<>(setA);
intersection.retainAll(setB); // intersection = A ∩ B
// Step 3: Remove intersection from union to get symmetric difference
result.removeAll(intersection);
System.out.println("Symmetric Difference: " + result);
// Output: [apple, date]
}
}
🧠 Explanation:
Step | Collection | Contents |
---|---|---|
addAll() | result = A ∪ B | [apple, banana, cherry, banana, date, cherry] |
retainAll() | intersection = A ∩ B | [banana, cherry] |
removeAll() | result - intersection | [apple, date] |
✔️ Duplicates will be handled correctly based on the underlying collection type (e.g. Set
vs List
).