Web / Apache Commons Collections Interview questions
What is the difference between SetUtils.union() and manually merging two sets?
SetUtils.union(setA, setB) returns a live, unmodifiable Set view that computes membership by delegating to the two original sets rather than eagerly copying every element into a new backing structure the moment it's called.
Set<String> teamA = Set.of("alice", "bob"); Set<String> teamB = Set.of("bob", "carol"); Set<String> combined = SetUtils.union(teamA, teamB); // view-based: [alice, bob, carol], no new backing collection allocated upfront Set<String> manual = new HashSet<>(teamA); manual.addAll(teamB); // eager copy: allocates and populates a brand-new HashSet immediately
A manual merge (new HashSet<>(setA); result.addAll(setB);) achieves the same logical membership, but it performs an eager copy right away, uses memory proportional to the combined size from that moment on, and produces an independent, owned collection with no further connection to the two source sets.
SetUtils.union() both sets still rely on their own equals()/hashCode() contracts to determine de-duplication, so choose the view-based union when you want a cheap, read-only combined perspective on data you don't intend to own or further mutate, and reach for the manual eager copy when you specifically need an independent, mutable result you can keep modifying afterward.
More Related questions...