Java Reference ยท Collections
Set operations in Java
How to compute union, intersection, difference and subset checks on Java sets with addAll, retainAll, removeAll and containsAll, without surprises.
Java has no union() or intersection() methods on Set. Instead, the bulk operations inherited from Collection do the same job, and each one modifies the set it is called on. To keep your inputs intact, copy first and then apply the operation to the copy.
The mapping is: addAll is union, retainAll is intersection, removeAll is difference and containsAll tests for a subset. Each returns a boolean telling you whether the receiving set changed (except containsAll, which answers the question itself).
Set<Integer> union = new TreeSet<>(a); union.addAll(b);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Operations
| Goal | Code | Mutates |
|---|---|---|
Union a โช b |
r = new HashSet<>(a); r.addAll(b); |
r only |
Intersection a โฉ b |
r = new HashSet<>(a); r.retainAll(b); |
r only |
Difference a โ b |
r = new HashSet<>(a); r.removeAll(b); |
r only |
Subset b โ a |
a.containsAll(b) |
nothing |
| Disjoint | Collections.disjoint(a, b) |
nothing |
Usage notes
- Copy before you call. Calling
a.retainAll(b)directly destroysa's other elements. This is the most common mistake. - Return value:
addAll,retainAllandremoveAllreturntrueonly if the receiver changed. - Argument type: the argument can be any
Collection, but aSetargument is much faster, becauseretainAllandremoveAllcallcontains()on it. Passing aListmakes the operationO(n*m). - A known pitfall:
AbstractSet.removeAllmay iterate over the argument instead of the set when the set is larger; with a slowcontains()on the argument this can be slow. Convert the argument to aHashSetif in doubt. - Immutable sets from
Set.of()throwUnsupportedOperationExceptionfor every mutating operation, even if nothing would change; copy into a mutable set first. - Result type decides order: use
TreeSetfor sorted output andLinkedHashSetto keep encounter order. - Equality:
set1.equals(set2)compares contents, so it tests whether two sets are identical.
Related
- HashSet, TreeSet, Set, Collection
- Lessons: HashSet, Collections framework