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 Set holds each element at most once, decided by equals and hashCode for hash-based sets, or by the comparator for sorted ones. The classic operations from set theory correspond to Collection bulk methods:

Set operations and their Java methods
OperationMeaningJavaSince
Union A ∪ BIn A or Ba.addAll(b)Java 1.2
Intersection A ∩ BIn botha.retainAll(b)Java 1.2
Difference A − BIn A but not Ba.removeAll(b)Java 1.2
Symmetric differenceIn exactly oneUnion minus intersectionJava 1.2
Subset testEvery element of B is in Aa.containsAll(b)Java 1.2
Disjoint testNothing in commonCollections.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);. Each element test is a contains call, so the cost depends on how fast contains is on the collection involved, as the last section shows.

Cost of the basic operations by set type
Setadd, contains, removeIteration orderBulk operation on sets of size n and m
HashSet, LinkedHashSetO(1) on averageHash order; insertion orderO(n) lookups into the other set
TreeSetO(log n)SortedO(n log m)
EnumSet, BitSetO(1), one bitOrdinal or numericOne word operation per 64 elements

Results that must not change afterwards can be frozen with Set.copyOf (Java 10), which also rejects null. Sets built with Set.of throw UnsupportedOperationException from retainAll, addAll and removeAll, so the copy-first pattern is required with them. All the examples were run on JDK 21.

Union, intersection and difference

The skills of two developers overlap in two places, which makes every operation produce a different, non-empty result.

Java
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:

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
  • retainAll kept the skills both know, git and sql. addAll produced the union, every skill on the team, once each.
  • removeAll gave the skills only Alice has. The symmetric difference, skills exactly one of them has, is the union minus the intersection.
  • containsAll tests for a subset and Collections.disjoint for no overlap.
  • Set.add returns false when the element is already present, which finds repeated words in one pass: to and be.
  • The results are printed sorted because the program uses TreeSet copies; with a HashSet the order would be arbitrary.

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.

Java
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:

Output
HashSet:       [apple, pear, kiwi, fig]
LinkedHashSet: [pear, apple, fig, kiwi]
TreeSet:       [apple, fig, kiwi, pear]
points:        2 distinct
case-insensitive TreeSet: [Go, Java]
  • HashSet iterates in hash order, LinkedHashSet in insertion order, and TreeSet in sorted order. The sets are backed by HashMap, LinkedHashMap and TreeMap, with the same costs; see TreeMap and LinkedHashMap.
  • Two records with the same coordinates count as one element, because records implement equals and hashCode by content. A class without them would keep both.
  • A TreeSet with String.CASE_INSENSITIVE_ORDER treats java and Java as the same element and keeps the first spelling added.
  • Enum elements belong in an EnumSet, which is a bit vector; see EnumSet 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.

Java
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:

Output
common: [4, 5]
only a: [1, 2, 3]
union size: 7
  • Filtering one set by other::contains gives the intersection, and by x -> !other.contains(x) the difference; the inputs are untouched.
  • 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 contains is a set.

The cost depends on the argument

Every bulk method calls contains many times, and contains on a List is a linear scan. The program intersects 200,000 numbers with 20,000 others passed as a set and as a list, then removes elements using a larger list as the argument. Each time is the fastest of three runs.

Java
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):

Output
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)
  • retainAll with a HashSet argument took at most a few tens of milliseconds, mostly copying the 200,000-element set first. With an ArrayList argument it took seconds: each of 200,000 elements was looked up by scanning a 20,000-element list.
  • 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.
  • removeAll has a documented trap. AbstractSet.removeAll iterates the set and calls contains on the argument when the argument is at least as large as the set. With a large List argument, that again means a list scan per element, and the call took seconds. removeIf(largerSet::contains) did the same job in milliseconds.
  • Rule: pass a Set, not a List, to retainAll, removeAll and containsAll, or wrap the list in new HashSet<>(list) first.

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 HashSet, adds objects that do not override equals, and puts the same BigDecimal values into a hash set and a tree set.

Java
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:

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 HashSet files each element in the bucket chosen by its hash code at the time of add. Renaming the tag from java to kotlin changed its hash code but not its bucket, so contains(t) looked in the wrong bucket and returned false, for the element itself and for an equal new one.
  • 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. remove found only the newly filed copy.
  • Objects that do not override equals and hashCode are compared by identity, so two objects that print the same are still two elements.
  • A TreeSet uses compareTo, not equals. BigDecimal values 1.0, 1.00 and 1 are three elements in a HashSet, because their scales differ, but one element in a TreeSet, because they compare as equal. The BigDecimal 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 equals and hashCode generated and cannot be changed after it is added, which removes the whole problem.

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.BitSet (Java 1.0) stores a set as one bit per possible value. Set operations become bitwise operations on whole 64-bit words. The program first shows the operations on ten users, then intersects two sets of a million random values below ten million, as bits and as HashSet<Integer>, keeping the fastest of three runs.

Java
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):

Output
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, andNot and xor are intersection, union, difference and symmetric difference. They change the BitSet they are called on, so the program clones it first, just as with retainAll. cardinality() counts the set bits.
  • stream() returns the members as an IntStream in ascending order, and nextSetBit(4) found 5, the first member at or after 4; a loop over nextSetBit visits the members without creating any objects.
  • Each BitSet of ten million bits takes 1.25 MB however many values it holds. A HashSet<Integer> of a million values needs tens of megabytes: an entry object, an Integer and a table slot per element.
  • The bitwise intersection processed 64 values per instruction and was ten to eighty times faster across runs than retainAll on the hash sets.
  • A BitSet 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, EnumSet.

Which operation to use

Choosing a set operation
GoalUse
Union, keeping inputsnew HashSet<>(a) then addAll(b)
Intersection, keeping inputsCopy, then retainAll(set); or filter the smaller by larger::contains
DifferenceCopy, then removeAll(set), or removeIf(other::contains)
Is B inside A?a.containsAll(b)
Any overlap?!Collections.disjoint(a, b)
Immutable inputsStream versions
Sorted resultsTreeSet
Insertion order keptLinkedHashSet
Argument is a large ListConvert it to a HashSet first

Removing duplicates from a list while keeping its order, which a plain HashSet cannot do, is covered on removing elements from a list.