Lesson 30 of 34 · Collections & Exceptions
Java HashSet and the Set Interface
Some questions are not about where something is, only about whether it is there: has this player already been invited? Which items do both chests contain? Is any number repeated? For those, Java has the Set — a collection that never contains the same element twice and answers "do you contain x?" instantly.
Creating a set
Set<String> tags = new HashSet<>();
System.out.println(tags.add("rare")); // true – added
System.out.println(tags.add("magic")); // true
System.out.println(tags.add("rare")); // false – already there
System.out.println(tags.size()); // 2
System.out.println(tags.contains("magic")); // true
tags.remove("magic");
add returns a boolean that tells you whether the set changed. That little detail is surprisingly useful, as you will see in the assignment.
Fast membership checks
list.contains(x) checks the elements one by one, so it gets slower as the list grows. HashSet.contains(x) jumps straight to the right place using the element's hashCode(), so it stays fast even with millions of elements. A classic use is a seen set:
Set<Integer> seen = new HashSet<>();
for (int n : new int[] {4, 8, 15, 8, 23}) {
if (!seen.add(n)) {
System.out.println("Repeated: " + n);
}
}
Repeated: 8
Removing all duplicates from a list is a one-liner: new HashSet<>(list).
HashSet, TreeSet, LinkedHashSet
Like HashMap, a HashSet has no defined order — printing it may list the elements in any order. Choose the implementation that matches your needs:
List<String> raw = List.of("pear", "apple", "fig", "apple");
System.out.println(new TreeSet<>(raw)); // [apple, fig, pear] sorted
System.out.println(new LinkedHashSet<>(raw)); // [pear, apple, fig] insertion order
Union, intersection, difference
Sets support the classic set operations through three methods. They modify the set you call them on, so work on a copy:
Set<String> mine = Set.of("sword", "shield", "potion");
Set<String> yours = Set.of("potion", "map", "sword");
Set<String> both = new TreeSet<>(mine);
both.retainAll(yours); // intersection → [potion, sword]
Set<String> all = new TreeSet<>(mine);
all.addAll(yours); // union → [map, potion, shield, sword]
Set<String> onlyMine = new TreeSet<>(mine);
onlyMine.removeAll(yours); // difference → [shield]
Two sets are equals when they contain the same elements, no matter which implementation or order — so new HashSet<>(List.of(1, 2)).equals(Set.of(2, 1)) is true.
Just like map keys, set elements rely on equals() and hashCode(). Strings, numbers and records work out of the box; your own classes must override both.
Common mistakes
- Expecting an order from a HashSet: use
TreeSet(sorted) orLinkedHashSet(insertion order) when order matters. - Destroying your input:
a.retainAll(b)changesa. Copy first:new HashSet<>(a). - Duplicates in
Set.of:Set.of("a", "a")throws anIllegalArgumentException. Usenew HashSet<>(List.of(...))for data that may repeat. - Changing an element after adding it: if a field used by
hashCode()changes, the set can no longer find the element.
Assignment
Implement three static methods in Main:
hasDuplicates(int[] numbers)returnstrueif any value appears more than once.hasDuplicates(new int[] {3, 1, 4, 1, 5})→true,hasDuplicates(new int[] {})→falsecommon(List<String> a, List<String> b)returns aSet<String>of the elements that appear in both lists. It must not modifyaorb.common(List.of("sword", "shield", "potion"), List.of("potion", "map", "sword"))→[potion, sword]firstRepeated(String[] words)returns the first word that appears for the second time when reading from left to right, ornullif no word repeats.firstRepeated(new String[] {"red", "blue", "green", "blue", "red"})→"blue"
Premium lesson
Unlock the full Learn Java course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Sets in other languages
- Python Sets and Set Operations · Python
Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.
Lesson last updated on .