TreeSet

Anonymous contributor's avatar
Anonymous contributor
Published Jun 10, 2024
Contribute to Docs

Tree set is a sorted collection that stores objects in a tree structure. It stores unique elements and sorts them in ascending order.

Syntax

Set <String> treeset = new TreeSet<>();

Example

In the following example, TreeSet is used to store string objects. It can be observed that the TreeSet iterates through the objects in an ascending order. It also doesn’t allow duplicate objects.

// Example.java
import java.util.*;
public class MyClass {
public static void main(String[] args) {
Set <String> treeset = new TreeSet<>();
treeset.add("Diablo III");
treeset.add("The Witcher");
treeset.add("Doom");
treeset.add("Doom");
System.out.println(treeset);
}
}

The above code results in the following output:

[Diablo III, Doom, The Witcher]

All contributors

Contribute to Docs

Learn Java on Codecademy