BitSet's and, or and xor mutate one BitSet in place using another as the mask, giving intersection, union and symmetric difference without writing a loop.
BitSet a = new BitSet();
a.set(1);
a.set(2);
a.set(3);
BitSet b = new BitSet();
b.set(2);
b.set(3);
b.set(4);
BitSet union = (BitSet) a.clone();
union.or(b);
BitSet intersection = (BitSet) a.clone();
intersection.and(b);
BitSet symDiff = (BitSet) a.clone();
symDiff.xor(b);
System.out.println("Union: " + union);
System.out.println("Intersection: " + intersection);
System.out.println("Symmetric difference: " + symDiff);
Union: {1, 2, 3, 4}
Intersection: {2, 3}
Symmetric difference: {1, 4}
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27