Lesson 3 of 616 minModule progress 0%

Module 11: Collections Framework in Practice

Sets for Uniqueness

Use sets to remove duplicates and check membership efficiently.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-17

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, manually edited for clarity, and checked against current Java documentation and runnable examples.

Learning goals

  • Choose between `HashSet`, `LinkedHashSet`, and `TreeSet`
  • Understand why sets do not use indexes
  • Use the right set for uniqueness plus ordering needs

Sets are about uniqueness, not position: If duplicates should collapse into one value, a set may be the right abstraction.

HashSet is the usual default: It is fast for membership tests and does not promise iteration order.

LinkedHashSet keeps insertion order, TreeSet keeps sorted order: Those ordering guarantees come with different tradeoffs.

Practical question: Do you need uniqueness only, uniqueness plus input order, or uniqueness plus sorted order?

Runnable examples

Duplicates are ignored in a set

java.util.Set<String> tags = new java.util.HashSet<>();
tags.add("java");
tags.add("java");
tags.add("streams");
System.out.println(tags.size());

Expected output

2

Mini exercise

Use a set to remove duplicate course tags from a list of repeated strings.

Summary

  • Sets are for uniqueness.
  • `HashSet` is the common default.
  • Choose other set types when order matters too.

Next step

After sets, move to maps when values must be found by key.

Sources used

Advertisement

Lesson check

When is a set the best fit?

Next lesson →