AI Hints
Home›Java Tutorial›HashMap, Looping Over a Map and HashSet
Java · Lesson 87 of 120

HashSet

No duplicates.

⏱ 2 min read▶ Video at 1:50:20🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

A set is a collection that never holds the same value twice. It's perfect for counting unique things, or quickly checking if something is there.

  • No duplicates
  • Unique values
  • Fast checks

Sets in action

We add ana twice. But a set keeps only one copy. Contains checks for a value, very quickly. A TreeSet keeps its values sorted. Retain all keeps only values found in both sets, an intersection. Run it. Three unique visitors. Ben visited, true. The numbers come out sorted. And eggs and tea are in both lists.

Main.javajava
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class Main {
    public static void main(String[] args) {
        Set<String> visitors = new HashSet<>();
        visitors.add("ana");
        visitors.add("ben");
        visitors.add("ana");
        visitors.add("chen");
        System.out.println(visitors.size() + " unique visitors");
        System.out.println("Ben visited? " + visitors.contains("ben"));
        Set<Integer> sorted = new TreeSet<>(Set.of(42, 7, 19, 3));
        System.out.println(sorted);
        Set<String> a = new TreeSet<>(Set.of("tea", "milk", "eggs"));
        a.retainAll(Set.of("eggs", "tea", "jam"));
        System.out.println("In both lists: " + a);
    }
}
Output
3 unique visitors
Ben visited? true
[3, 7, 19, 42]
In both lists: [eggs, tea]

Choosing a collection

These three collections cover most programs. A list keeps order, and allows duplicates. A set has no duplicates. And a map links keys to values.

NeedUse
Ordered items, duplicates OKArrayList
Unique itemsHashSet / TreeSet
Look up by keyHashMap / TreeMap

Summary

A set holds unique values, and checks membership fast. Use HashSet for speed, and TreeSet for order. Next, sorting.

Key takeaways
  • Set<T>
  • No duplicates
  • TreeSet is sorted
Next up: Sorting with Comparator — sort your way