Skip to content
Tutorials Center
My learning

Topics

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).

Java
Set<Integer> union = new TreeSet<>(a);
union.addAll(b);

Try it

Java Union, intersection and difference

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.

Java Subsets, disjoint sets and the return values

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 destroys a's other elements. This is the most common mistake.
  • Return value: addAll, retainAll and removeAll return true only if the receiver changed.
  • Argument type: the argument can be any Collection, but a Set argument is much faster, because retainAll and removeAll call contains() on it. Passing a List makes the operation O(n*m).
  • A known pitfall: AbstractSet.removeAll may iterate over the argument instead of the set when the set is larger; with a slow contains() on the argument this can be slow. Convert the argument to a HashSet if in doubt.
  • Immutable sets from Set.of() throw UnsupportedOperationException for every mutating operation, even if nothing would change; copy into a mutable set first.
  • Result type decides order: use TreeSet for sorted output and LinkedHashSet to keep encounter order.
  • Equality: set1.equals(set2) compares contents, so it tests whether two sets are identical.