Collections: set algebra with retainAll and removeAll

retainAll is intersection, removeAll is difference and addAll is union. Copy first, because these methods mutate the receiver.

Code
var a = new TreeSet<>(List.of(1, 2, 3, 4));
var b = Set.of(3, 4, 5);

var union = new TreeSet<>(a); union.addAll(b);
var intersection = new TreeSet<>(a); intersection.retainAll(b);
var difference = new TreeSet<>(a); difference.removeAll(b);

System.out.println("union        = " + union);
System.out.println("intersection = " + intersection);
System.out.println("difference   = " + difference);
System.out.println("original a unchanged = " + a);
Output
union        = [1, 2, 3, 4, 5]
intersection = [3, 4]
difference   = [1, 2]
original a unchanged = [1, 2, 3, 4]
Advertisement

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-07-30