Java TreeSet
Java TreeSet
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:
Remove an Element
Use remove()
to remove an element:
Remove All Elements
Use clear()
to remove all elements:
TreeSet Size
Use size()
to count how many unique elements are in the set:
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
Feature | HashSet |
TreeSet |
---|---|---|
Order | No guaranteed order | Sorted (natural order) |
Duplicates | Not allowed | Not allowed |
Performance | Faster (no sorting) | Slower (due to sorting) |
Tip: Use HashSet
when you care about speed, and TreeSet
when you need sorted elements.