bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Data Structures
Java•Java Data Structures

Java TreeSet

Native lesson simulator

Hash map lookup

Hash the key, jump to a bucket, then compare entries there.

Ada -> bucket 20Cy:21Bo:22Ada:3Dee:33

Ada hashes to bucket 2; lookup only scans entries in that bucket.

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java TreeSet?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

import java.util.TreeSet; // Import the TreeSet ___
3Order

Put the learning moves in the order that makes the concept easiest to apply.

Loop Through a TreeSet
Remove All Elements
Check if an Element Exists

A TreeSet is a collection that stores unique elements in sorted order .

It is part of the java.util package and implements the Set interface.

Tip

Unlike HashSet , which has no order, TreeSet keeps its elements sorted automatically.

Create a TreeSet

Example

Create a TreeSet object called cars that will store strings:

import java.util.TreeSet; // Import the TreeSet class
TreeSet<String> cars = new TreeSet<>();

Now you can use methods like add() , contains() , and remove() to manage your sorted set of elements.

Add Elements

To add elements to a TreeSet , use the add() method:

Example

import java.util.TreeSet;
public class Main {
  public static void main(String[] args) {
    TreeSet<String> cars = new TreeSet<>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("BMW");  // Duplicate
    cars.add("Mazda");
    System.out.println(cars);
  }
}

Output: The elements will be sorted automatically (e.g., [BMW, Ford, Mazda, Volvo]).

Note

Duplicates like "BMW" will only appear once.

Check if an Element Exists

Use contains() to check if an element exists:

cars.contains("Mazda");

Remove an Element

Use remove() to remove an element

cars.remove("Volvo");

Remove All Elements

Use clear() to remove all elements

cars.clear();

TreeSet Size

Use size() to count how many unique elements are in the set:

cars.size();

Note

Duplicate values are not counted - only unique elements are included in the size.

Loop Through a TreeSet

Loop through the elements of a TreeSet with a for-each loop:

Example

TreeSet<String> cars = new TreeSet<>();
// add elements...
for (String i : cars) {
  System.out.println(i);
}

Using TreeSet with Numbers

TreeSet also works with numbers and sorts them from smallest to largest:

Example

import java.util.TreeSet;
public class Main {
  public static void main(String[] args) {
    TreeSet<Integer> numbers = new TreeSet<>();
    numbers.add(40);
    numbers.add(10);
    numbers.add(30);
    numbers.add(20);
    for (int n : numbers) {
      System.out.println(n);
    }
}
}

Output: The numbers will be printed in sorted order (10, 20, 30, 40).

HashSet vs TreeSet

FeatureHashSetTreeSet
OrderNo guaranteed orderSorted (natural order)
DuplicatesNot allowedNot allowed
PerformanceFaster (no sorting)Slower (due to sorting)

Tip

Use HashSet when you care about speed, and TreeSet when you need sorted elements.

The var Keyword

From Java 10, you can use the var keyword to declare a TreeSet variable without writing the type twice. The compiler figures out the type from the value you assign.

This makes code shorter, but many developers still use the full type for clarity . Since var is valid Java, you may see it in other code, so it's good to know that it exists:

// Without var TreeSet<String> cars = new TreeSet<String>();
// With var var cars = new TreeSet<String>();

The Set Interface

Note

Sometimes you will see both Set and TreeSet in Java code, like this:

import java.util.Set;
import java.util.TreeSet;
Set<String> cars = new TreeSet<>();

This means the variable (cars) is declared as a Set (the interface), but it stores a TreeSet object (the actual set). Since TreeSet implements the Set interface, this is possible.

It works the same way, but some developers prefer this style because it gives them more flexibility to change the type later.

Previous

Java HashSet

Next

Java LinkedHashSet