Skip to lesson

Union, intersection and difference

Sets can be combined like the sets in maths class: union (in either), intersection (in both) and difference (in the first but not the second). Java does each with one method call.

Set maths in Java

Union is every value in A or B. Intersection is the values in both A and B. Difference (A minus B) is the values in A that are not in B.

Picture two circles that overlap, one for the Java class and one for the Python class. Students in the overlap take both. Each set operation picks a part of that picture. The code below builds the union.

Java
Set<String> java = Set.of("Aarav", "Diya", "Kabir");Set<String> python = Set.of("Diya", "Kabir", "Isha");Set<String> either = new TreeSet<>(java);either.addAll(python);   // union: Aarav, Diya, Isha, Kabir
  • Union, "in A or B": a.addAll(b).
  • Intersection, "in both A and B": a.retainAll(b). Retain means keep: keep only what is also in b.
  • Difference, "in A but not in B": a.removeAll(b).
  • Subset, "is every value of B also in A?": a.containsAll(b) returns true or false.
Two overlapping circles, A (Java class) and B (Python class). Union is the whole drawing, intersection is the overlap, and difference A minus B is the part of A outside B.

Example 1 · Union, intersection and difference

SetMathsDemo.javaJava
import java.util.Set;import java.util.TreeSet;
public class SetMathsDemo {    public static void main(String[] args) {        Set<Integer> a = new TreeSet<>(Set.of(1, 2, 3, 4, 5));        Set<Integer> b = new TreeSet<>(Set.of(4, 5, 6, 7));
        Set<Integer> union = new TreeSet<>(a);        union.addAll(b);
        Set<Integer> both = new TreeSet<>(a);        both.retainAll(b);
        Set<Integer> onlyA = new TreeSet<>(a);        onlyA.removeAll(b);
        System.out.println("A: " + a + "  B: " + b);        System.out.println("A union B: " + union);        System.out.println("A intersect B: " + both);        System.out.println("A minus B: " + onlyA);        System.out.println("A contains all of {2, 3}? " + a.containsAll(Set.of(2, 3)));        System.out.println("A contains all of B? " + a.containsAll(b));    }}
Output
A: [1, 2, 3, 4, 5]  B: [4, 5, 6, 7]
A union B: [1, 2, 3, 4, 5, 6, 7]
A intersect B: [4, 5]
A minus B: [1, 2, 3]
A contains all of {2, 3}? true
A contains all of B? false

What this code does

  • Each result starts as a copy of a, so a and b are the same at the end as at the start.
  • Set.of has no fixed order, so the values are copied into a TreeSet before anything is printed.

Copy first, then change

The first three methods change the set you call them on. After java.retainAll(python), the java set holds only the students who take both. The full Java class list is gone.

Example 2 · Mistake: retainAll changes the original

LostDataDemo.javaJava
import java.util.Set;import java.util.TreeSet;
public class LostDataDemo {    public static void main(String[] args) {        Set<String> cricket = new TreeSet<>(Set.of("Aman", "Bhavya", "Chirag", "Dev"));        Set<String> football = new TreeSet<>(Set.of("Chirag", "Dev", "Esha"));
        cricket.retainAll(football);        System.out.println("In both teams: " + cricket);
        System.out.println("Cricket team: " + cricket);        Set<String> sportsDay = new TreeSet<>(cricket);        sportsDay.addAll(football);        System.out.println("Sports day list: " + sportsDay);    }}
Output
In both teams: [Chirag, Dev]
Cricket team: [Chirag, Dev]
Sports day list: [Chirag, Dev, Esha]

What this code does

  • retainAll was called on cricket itself, so Aman and Bhavya were removed from the cricket team. The later union is wrong too: it should have 5 names.
  • Fix: Set<String> both = new TreeSet<>(cricket); both.retainAll(football);. Then cricket keeps all four players.

So the usual pattern is: make a copy, then change the copy. Set<String> both = new TreeSet<>(java); both.retainAll(python); leaves java and python untouched. Copying into a TreeSet also gives a sorted, readable result.

The methods return a boolean: true if the set changed. addAll returns false when nothing new was added, and retainAll returns false when every value was already in the other set.

Predict the output

Copy first, then change

Read the code and pick what it prints.

Round 1 of 2

What is printed?

Set<String> java = new TreeSet<>(List.of("Aarav", "Diya", "Kabir"));
Set<String> python = new TreeSet<>(List.of("Diya", "Isha"));
java.retainAll(python);
System.out.println(java);

Building bigger questions

Real questions often combine two steps. "In exactly one of the two clubs" (the symmetric difference) is the union minus the intersection. "Friend suggestions for Aarav" are his friends' friends, minus the people he already knows, minus Aarav himself.

Example 3 · Common friends and suggestions

FriendsDemo.javaJava
import java.util.Set;import java.util.TreeSet;
public class FriendsDemo {    public static void main(String[] args) {        Set<String> aarav = new TreeSet<>(Set.of("Diya", "Kabir", "Meera", "Rohan"));        Set<String> diya = new TreeSet<>(Set.of("Aarav", "Kabir", "Isha", "Rohan", "Zoya"));
        Set<String> mutual = new TreeSet<>(aarav);        mutual.retainAll(diya);        System.out.println("Mutual friends: " + mutual);
        Set<String> suggestions = new TreeSet<>(diya);        suggestions.removeAll(aarav);        suggestions.remove("Aarav");        System.out.println("People Aarav may know: " + suggestions);
        Set<String> everyone = new TreeSet<>(aarav);        everyone.addAll(diya);        System.out.println("Party invite list: " + everyone.size() + " people");    }}
Output
Mutual friends: [Kabir, Rohan]
People Aarav may know: [Isha, Zoya]
Party invite list: 7 people

What this code does

  • Mutual friends are an intersection. Suggestions are Diya's friends minus Aarav's friends, minus Aarav himself.
  • The invite list is a union: 4 + 5 names, minus the 2 shared ones, gives 7. Aarav and Diya are each on the other's list, so both are counted.

Example 4 · Course enrolments

EnrolmentDemo.javaJava
import java.util.Set;import java.util.TreeSet;
public class EnrolmentDemo {    public static void main(String[] args) {        Set<String> java = new TreeSet<>(Set.of("Arjun", "Isha", "Kavya", "Neha", "Vikram"));        Set<String> python = new TreeSet<>(Set.of("Isha", "Manav", "Neha", "Sara"));
        Set<String> both = new TreeSet<>(java);        both.retainAll(python);
        Set<String> either = new TreeSet<>(java);        either.addAll(python);
        Set<String> onlyJava = new TreeSet<>(java);        onlyJava.removeAll(python);
        Set<String> exactlyOne = new TreeSet<>(either);        exactlyOne.removeAll(both);
        System.out.println("Both courses: " + both);        System.out.println("Students in total: " + either.size());        System.out.println("Only Java: " + onlyJava);        System.out.println("Exactly one course: " + exactlyOne);
        Set<String> toppers = Set.of("Isha", "Kavya");        System.out.println("All toppers in Java? " + java.containsAll(toppers));        System.out.println("All toppers in Python? " + python.containsAll(toppers));    }}
Output
Both courses: [Isha, Neha]
Students in total: 7
Only Java: [Arjun, Kavya, Vikram]
Exactly one course: [Arjun, Kavya, Manav, Sara, Vikram]
All toppers in Java? true
All toppers in Python? false

What this code does

  • "Exactly one course" is built from two earlier results: everyone (union) minus those in both (intersection).
  • containsAll answers a yes/no question about a whole group at once. Kavya is not in Python, so the second answer is false.

Two sets are equal when they hold the same values, whatever their class or order. So a HashSet and a TreeSet with the same three numbers are equals. This makes equals a quick way to check "did both students choose exactly the same subjects?"

Order of execution

Friend suggestions in order

Put the steps for "friends of friends" in order.

They work with lists too

addAll, removeAll, retainAll and containsAll are Collection methods, so lists have them as well, and the argument can be any collection. list.removeAll(blocked) removes every copy of each blocked value from the list.

Example 5 · Missing documents for hostel admission

AdmissionDemo.javaJava
import java.util.Set;import java.util.TreeSet;
public class AdmissionDemo {    static final Set<String> REQUIRED = Set.of("Aadhaar", "Marksheet", "Photo", "Fee receipt");
    static void check(String student, Set<String> submitted) {        if (submitted.containsAll(REQUIRED)) {            System.out.println(student + ": complete");        } else {            Set<String> missing = new TreeSet<>(REQUIRED);            missing.removeAll(submitted);            System.out.println(student + ": missing " + missing);        }    }
    public static void main(String[] args) {        check("Priya", Set.of("Photo", "Aadhaar", "Fee receipt", "Marksheet"));        check("Rahul", Set.of("Photo", "Aadhaar"));        check("Sneha", Set.of("Aadhaar", "Marksheet", "Photo", "Fee receipt", "Income certificate"));    }}
Output
Priya: complete
Rahul: missing [Fee receipt, Marksheet]
Sneha: complete

What this code does

  • containsAll checks every required document in one call, whatever order the student handed them in.
  • Extra documents do not matter: Sneha's set contains all the required ones, so she is complete. The missing list is a difference: required minus submitted.

Example 6 · Cleaning a list and comparing sets

CleanAndCompareDemo.javaJava
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;import java.util.TreeSet;
public class CleanAndCompareDemo {    public static void main(String[] args) {        List<String> words = new ArrayList<>(List.of("this", "is", "a", "silly", "test", "silly", "idea"));        Set<String> blocked = new HashSet<>(List.of("silly", "stupid"));
        words.removeAll(blocked);        System.out.println("Clean message: " + words);
        Set<String> priya = new HashSet<>(List.of("Physics", "Maths", "CS"));        Set<String> rohan = new TreeSet<>(List.of("CS", "Maths", "Physics"));        Set<String> kavya = new TreeSet<>(List.of("CS", "Maths", "Biology"));
        System.out.println("Priya and Rohan same subjects? " + priya.equals(rohan));        System.out.println("Priya and Kavya same subjects? " + priya.equals(kavya));    }}
Output
Clean message: [this, is, a, test, idea]
Priya and Rohan same subjects? true
Priya and Kavya same subjects? false

What this code does

  • removeAll on a list removes both copies of silly. The blocked words are a HashSet, so each check inside removeAll is fast.
  • Set equals compares only the values. A HashSet and a TreeSet with the same three subjects are equal, in any order.

These methods call contains on the argument again and again. On a list argument each call scans the list. On a HashSet argument each call is O(1), so passing a set is much faster for big data.

Next step

Check your understanding

12 quick questions