Set Operations
Union, intersection and difference map directly onto the bulk methods of Java's Set interface: addAll, retainAll and removeAll. Those methods change the set they are called on, and their speed depends on what kind of collection is passed in. This page explains the mapping, compares the set implementations, shows the stream equivalents, and measures a performance trap in removeAll.
Contents
Set algebra with the Set interface
A SetequalshashCodeCollection
| Operation | Meaning | Java | Since |
|---|---|---|---|
| Union A ∪ B | In A or B | a.addAll(b) | Java 1.2 |
| Intersection A ∩ B | In both | a.retainAll(b) | Java 1.2 |
| Difference A − B | In A but not B | a.removeAll(b) | Java 1.2 |
| Symmetric difference | In exactly one | Union minus intersection | Java 1.2 |
| Subset test | Every element of B is in A | a.containsAll(b) | Java 1.2 |
| Disjoint test | Nothing in common | Collections.disjoint(a, b) | Java 5 |
The bulk methods change the set they are called on and return whether it changed. To keep the inputs, copy first: Set<T> both = new HashSet<>(a); both.retainAll(b);containscontains
| Set | addcontainsremove | Iteration order | Bulk operation on sets of size n and m |
|---|---|---|---|
HashSetLinkedHashSet | O(1) on average | Hash order; insertion order | O(n) lookups into the other set |
TreeSet | O(log n) | Sorted | O(n log m) |
EnumSetBitSet | O(1), one bit | Ordinal or numeric | One word operation per 64 elements |
Results that must not change afterwards can be frozen with Set.copyOfnullSet.ofUnsupportedOperationExceptionretainAlladdAllremoveAll
Union, intersection and difference
The skills of two developers overlap in two places, which makes every operation produce a different, non-empty result.
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class SetAlgebra {
public static void main(String[] args) {
Set<String> alice = Set.of("java", "sql", "docker", "git");
Set<String> bob = Set.of("python", "sql", "git", "aws");
// Each operation copies first, because retainAll/addAll/removeAll change the set
Set<String> both = new TreeSet<>(alice);
both.retainAll(bob);
System.out.println("intersection (both know): " + both);
Set<String> either = new TreeSet<>(alice);
either.addAll(bob);
System.out.println("union (team knows): " + either);
Set<String> onlyAlice = new TreeSet<>(alice);
onlyAlice.removeAll(bob);
System.out.println("difference (only alice): " + onlyAlice);
Set<String> exactlyOne = new TreeSet<>(either);
exactlyOne.removeAll(both);
System.out.println("symmetric difference: " + exactlyOne);
System.out.println("alice knows git and sql? " + alice.containsAll(Set.of("git", "sql")));
System.out.println("no skill in common with {rust}? "
+ Collections.disjoint(alice, Set.of("rust")));
// add returns false for a duplicate: a one-line duplicate check
Set<String> seen = new HashSet<>();
for (String w : "to be or not to be".split(" ")) {
if (!seen.add(w)) {
System.out.println("repeat: " + w);
}
}
}
}
Output:
intersection (both know): [git, sql]
union (team knows): [aws, docker, git, java, python, sql]
difference (only alice): [docker, java]
symmetric difference: [aws, docker, java, python]
alice knows git and sql? true
no skill in common with {rust}? true
repeat: to
repeat: be
kept the skills both know,retainAll andgit .sql produced the union, every skill on the team, once each.addAll gave the skills only Alice has. The symmetric difference, skills exactly one of them has, is the union minus the intersection.removeAll tests for a subset andcontainsAll for no overlap.Collections.disjoint returnsSet.add when the element is already present, which finds repeated words in one pass:false andto .be- The results are printed sorted because the program uses
copies; with aTreeSet the order would be arbitrary.HashSet
HashSet, LinkedHashSet and TreeSet
The same fruit names go into three set types, and two more examples show how each set decides that two elements are the same.
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class SetTypes {
record Point(int x, int y) {
}
public static void main(String[] args) {
List<String> input = List.of("pear", "apple", "fig", "apple", "kiwi", "pear");
System.out.println("HashSet: " + new HashSet<>(input));
System.out.println("LinkedHashSet: " + new LinkedHashSet<>(input));
System.out.println("TreeSet: " + new TreeSet<>(input));
// Duplicates are decided by equals/hashCode: records get both for free
Set<Point> points = new HashSet<>(
List.of(new Point(1, 2), new Point(1, 2), new Point(3, 4)));
System.out.println("points: " + points.size() + " distinct");
// A TreeSet decides duplicates by compareTo, not equals
Set<String> ignoreCase = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
ignoreCase.addAll(List.of("Java", "JAVA", "java", "Go"));
System.out.println("case-insensitive TreeSet: " + ignoreCase);
}
}
Output:
HashSet: [apple, pear, kiwi, fig]
LinkedHashSet: [pear, apple, fig, kiwi]
TreeSet: [apple, fig, kiwi, pear]
points: 2 distinct
case-insensitive TreeSet: [Go, Java]
iterates in hash order,HashSet in insertion order, andLinkedHashSet in sorted order. The sets are backed byTreeSet ,HashMap andLinkedHashMap , with the same costs; seeTreeMapTreeMap and LinkedHashMap .- Two records with the same coordinates count as one element, because records implement
andequals by content. A class without them would keep both.hashCode - A
withTreeSet treatsString.CASE_INSENSITIVE_ORDER andjava as the same element and keeps the first spelling added.Java - Enum elements belong in an
, which is a bit vector; seeEnumSetEnumSet and EnumMap .
Set operations with streams
Streams express the same operations without changing any input, which suits immutable sets such as those from Set.of
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamSets {
public static void main(String[] args) {
List<Integer> a = List.of(1, 2, 3, 4, 5);
Set<Integer> b = Set.of(4, 5, 6, 7);
// Without changing either input
List<Integer> common = a.stream().filter(b::contains).toList();
List<Integer> onlyA = a.stream().filter(x -> !b.contains(x)).toList();
Set<Integer> all = Stream.concat(a.stream(), b.stream()).collect(Collectors.toSet());
System.out.println("common: " + common);
System.out.println("only a: " + onlyA);
System.out.println("union size: " + all.size());
}
}
Output:
common: [4, 5]
only a: [1, 2, 3]
union size: 7
- Filtering one set by
gives the intersection, and byother::contains the difference; the inputs are untouched.x -> !other.contains(x) - Concatenating two streams and collecting to a set gives the union, here 7 distinct values.
- The stream versions are also the way to do set operations on lists, as long as the collection passed to
is a set.contains
The cost depends on the argument
Every bulk method calls containscontainsList
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
public class SetOpCost {
public static void main(String[] args) {
Set<Integer> big = new HashSet<>();
for (int i = 0; i < 200000; i++) {
big.add(i);
}
List<Integer> otherList = new ArrayList<>();
for (int i = 100000; i < 120000; i++) {
otherList.add(i);
}
Set<Integer> otherSet = new HashSet<>(otherList);
System.out.println("intersection of 200,000 and 20,000 elements:");
time("retainAll(HashSet)", () -> {
Set<Integer> s = new HashSet<>(big);
s.retainAll(otherSet);
return s.size();
});
time("retainAll(ArrayList)", () -> {
Set<Integer> s = new HashSet<>(big);
s.retainAll(otherList);
return s.size();
});
time("stream filter contains", () -> (int) otherList.stream().filter(big::contains)
.count());
System.out.println("removeAll with a larger List argument:");
List<Integer> largerList = new ArrayList<>(big);
largerList.add(-1);
Set<Integer> small = new HashSet<>(otherSet);
time("small.removeAll(largerList)", () -> {
Set<Integer> s = new HashSet<>(small);
s.removeAll(largerList);
return s.size();
});
time("removeIf(largerSet::contains)", () -> {
Set<Integer> largerSet = new HashSet<>(largerList);
Set<Integer> s = new HashSet<>(small);
s.removeIf(largerSet::contains);
return s.size();
});
}
// Best of 3 runs
static void time(String name, Supplier<Integer> op) {
long best = Long.MAX_VALUE;
int size = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
size = op.get();
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-30s %8.1f ms (result size %,d)%n", name, best / 1e6, size);
}
}
Output (2-CPU Linux machine, JDK 21; the times are approximate):
intersection of 200,000 and 20,000 elements:
retainAll(HashSet) 11.2 ms (result size 20,000)
retainAll(ArrayList) 2013.1 ms (result size 20,000)
stream filter contains 0.5 ms (result size 20,000)
removeAll with a larger List argument:
small.removeAll(largerList) 3498.4 ms (result size 0)
removeIf(largerSet::contains) 7.3 ms (result size 0)
with aretainAll argument took at most a few tens of milliseconds, mostly copying the 200,000-element set first. With anHashSet argument it took seconds: each of 200,000 elements was looked up by scanning a 20,000-element list.ArrayList- Filtering the smaller collection against the larger set was the fastest, because it does only 20,000 hash lookups. Iterate the smaller side and look up in the larger one.
has a documented trap.removeAll iterates the set and callsAbstractSet.removeAll on the argument when the argument is at least as large as the set. With a largecontains argument, that again means a list scan per element, and the call took seconds.List did the same job in milliseconds.removeIf(largerSet::contains)- Rule: pass a
, not aSet , toList ,retainAll andremoveAll , or wrap the list incontainsAll first.new HashSet<>(list)
What makes two elements equal: mutable elements and compareTo
A set's behaviour depends entirely on how its elements define equality. The program changes an element after adding it to a HashSetequalsBigDecimal
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
public class MutableElements {
// A mutable class with equals and hashCode based on its fields
static final class Tag {
String name;
Tag(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
return o instanceof Tag t && t.name.equals(name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public String toString() {
return name;
}
}
public static void main(String[] args) {
Set<Tag> tags = new HashSet<>();
Tag t = new Tag("java");
tags.add(t);
t.name = "kotlin"; // changes the hash code
System.out.println("set: " + tags + ", contains(t): " + tags.contains(t)
+ ", contains(new Tag(kotlin)): " + tags.contains(new Tag("kotlin")));
tags.add(t); // the same object goes in a second time
System.out.println("after adding t again: " + tags + " size " + tags.size());
System.out.println("remove(t): " + tags.remove(t) + ", size now " + tags.size());
// Without equals/hashCode, equal-looking objects are all distinct
Set<Object> plain = new HashSet<>();
plain.add(new Object() {
@Override
public String toString() {
return "x";
}
});
plain.add(new Object() {
@Override
public String toString() {
return "x";
}
});
System.out.println("objects without equals: " + plain.size() + " elements " + plain);
// A TreeSet uses compareTo, which may disagree with equals
Set<java.math.BigDecimal> hash = new HashSet<>();
Set<java.math.BigDecimal> tree = new TreeSet<>();
for (String v : new String[] {"1.0", "1.00", "1"}) {
hash.add(new java.math.BigDecimal(v));
tree.add(new java.math.BigDecimal(v));
}
System.out.println("BigDecimal 1.0, 1.00, 1: HashSet " + hash.size() + ", TreeSet "
+ tree.size());
}
}
Output:
set: [kotlin], contains(t): false, contains(new Tag(kotlin)): false
after adding t again: [kotlin, kotlin] size 2
remove(t): true, size now 1
objects without equals: 2 elements [x, x]
BigDecimal 1.0, 1.00, 1: HashSet 3, TreeSet 1
- A
files each element in the bucket chosen by its hash code at the time ofHashSet . Renaming the tag fromadd tojava changed its hash code but not its bucket, sokotlin looked in the wrong bucket and returnedcontains(t) , for the element itself and for an equal new one.false - Because the set no longer finds it, adding the same object again stored it a second time: the set now holds two entries for one object, which breaks the basic promise of a set.
found only the newly filed copy.remove - Objects that do not override
andequals are compared by identity, so two objects that print the same are still two elements.hashCode - A
usesTreeSet , notcompareTo .equals values 1.0, 1.00 and 1 are three elements in aBigDecimal , because their scales differ, but one element in aHashSet , because they compare as equal. TheTreeSetBigDecimal page explains why.
Use immutable elements in sets: strings, numbers, records with immutable fields, or enums. If an element must change, remove it first, change it, and add it again. A record whose components are themselves immutable gets correct equalshashCode
Integer sets as bits: BitSet
When the elements are non-negative integers from a known range, such as user IDs or feature flags by index, java.util.BitSetHashSet<Integer>
import java.util.BitSet;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.function.IntSupplier;
public class BitSetOps {
public static void main(String[] args) {
// Small example: users 0..9 with two features enabled
BitSet darkMode = new BitSet();
BitSet beta = new BitSet();
for (int u : new int[] {1, 2, 5, 7}) {
darkMode.set(u);
}
for (int u : new int[] {2, 3, 7, 9}) {
beta.set(u);
}
BitSet both = (BitSet) darkMode.clone();
both.and(beta);
BitSet either = (BitSet) darkMode.clone();
either.or(beta);
BitSet onlyDark = (BitSet) darkMode.clone();
onlyDark.andNot(beta);
BitSet exactlyOne = (BitSet) darkMode.clone();
exactlyOne.xor(beta);
System.out.println("and " + both + ", or " + either + ", andNot " + onlyDark
+ ", xor " + exactlyOne + ", cardinality(or) " + either.cardinality());
System.out.println("stream() of the union: " + either.stream().boxed().toList()
+ ", nextSetBit(4) = " + either.nextSetBit(4));
// Large example: two sets of ints drawn from 0..9,999,999
Random r = new Random(7);
int[] aVals = r.ints(1000000, 0, 10000000).toArray();
int[] bVals = r.ints(1000000, 0, 10000000).toArray();
BitSet a = new BitSet(10000000);
BitSet b = new BitSet(10000000);
Set<Integer> ha = new HashSet<>();
Set<Integer> hb = new HashSet<>();
for (int i = 0; i < aVals.length; i++) {
a.set(aVals[i]);
b.set(bVals[i]);
ha.add(aVals[i]);
hb.add(bVals[i]);
}
System.out.printf("BitSet memory: %.1f MB for two sets (%,d bits each)%n",
2 * a.size() / 8.0 / 1e6, a.size());
time("BitSet and", () -> {
BitSet c = (BitSet) a.clone();
c.and(b);
return c.cardinality();
});
time("HashSet retainAll", () -> {
Set<Integer> c = new HashSet<>(ha);
c.retainAll(hb);
return c.size();
});
}
// Best of 3 runs
static void time(String name, IntSupplier f) {
long best = Long.MAX_VALUE;
int result = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
result = f.getAsInt();
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-18s %7.1f ms (%,d in common)%n", name, best / 1e6, result);
}
}
Output (approximate timings, 2-CPU Linux machine, JDK 21):
and {2, 7}, or {1, 2, 3, 5, 7, 9}, andNot {1, 5}, xor {1, 3, 5, 9}, cardinality(or) 6
stream() of the union: [1, 2, 3, 5, 7, 9], nextSetBit(4) = 5
BitSet memory: 2.5 MB for two sets (10,000,000 bits each)
BitSet and 5.0 ms (90,561 in common)
HashSet retainAll 130.7 ms (90,561 in common)
,and ,or andandNot are intersection, union, difference and symmetric difference. They change thexor they are called on, so the program clones it first, just as withBitSet .retainAll counts the set bits.cardinality() returns the members as anstream() in ascending order, andIntStream found 5, the first member at or after 4; a loop overnextSetBit(4) visits the members without creating any objects.nextSetBit- Each
of ten million bits takes 1.25 MB however many values it holds. ABitSet of a million values needs tens of megabytes: an entry object, anHashSet<Integer> and a table slot per element.Integer - The bitwise intersection processed 64 values per instruction and was ten to eighty times faster across runs than
on the hash sets.retainAll - A
only fits dense, non-negative integer ranges: one value near a billion would make it allocate a billion bits. Enum constants have their own bit-vector set,BitSet .EnumSet
Which operation to use
| Goal | Use |
|---|---|
| Union, keeping inputs | new HashSet<>(a)addAll(b) |
| Intersection, keeping inputs | Copy, then retainAll(set)larger::contains |
| Difference | Copy, then removeAll(set)removeIf(other::contains) |
| Is B inside A? | a.containsAll(b) |
| Any overlap? | !Collections.disjoint(a, b) |
| Immutable inputs | Stream versions |
| Sorted results | TreeSet |
| Insertion order kept | LinkedHashSet |
| Argument is a large List | Convert it to a HashSet |
Removing duplicates from a list while keeping its order, which a plain HashSet