Java TreeSet

Java TreeSet


TreeSet can not contain null values and are slower than HashSet.
TreeSet contains only unique values and elements are sorted in ascending order.
The following example shows how to create a TreeSet and add elements to it.


import java.util.TreeSet;

public class TreeSetAddExample {
    public static void main(String[] args) {
        TreeSet<String> cars = new TreeSet<>();

        cars.add("BMW");
        cars.add("Volvo");
        cars.add("Audi");
        cars.add("Mercedes");
        cars.add("Nissan");
        cars.add("Nissan");
        
        System.out.println("Cars : " + cars);
    }
}

Output:


$ javac TreeSetAddExample.java
$ java TreeSetAddExample
Cars : [Audi, BMW, Mercedes, Nissan, Volvo]


The following example shows how to use a few TreeSet methods to check the size of the TreeSet, if it's empty and remove elements.


import java.util.TreeSet;

public class TreeSetSimpleMethods {
    public static void main(String[] args) {
        TreeSet<String> cars = new TreeSet<>();

        cars.add("BMW");
        cars.add("Volvo");
        cars.add("Audi");
        cars.add("Mercedes");
        cars.add("Nissan");
        cars.add("Candy");

        System.out.println("Cars : " + cars);

        System.out.println("Removing 'candy'");
        cars.remove("Candy");

        System.out.println("\nCars : " + cars);

        System.out.println("Size : " + cars.size());

        System.out.println("first: " + cars.first());
        System.out.println("last: " + cars.last());

        // check if TreeSet is empty
        System.out.println("Is Empty: " + cars.isEmpty());

        // clear() will remove everything from the TreeSet
        cars.clear();
        System.out.println("Is Empty: " + cars.isEmpty());
    }
}


add() method will add element to the TreeSet if not already present.
remove() method will remove element if the specified key is present.
size() method will return the number of elements in the TreeSet.
first() method will return the first element in the TreeSet.
last() method will return the last element in the TreeSet.
isEmpty() will return true if the TreeSet is empty.
clear() method will remove all elements from the TreeSet.

Output:


$ javac TreeSetSimpleMethods.java
$ java TreeSetSimpleMethods
Cars : [Audi, BMW, Candy, Mercedes, Nissan, Volvo]
Removing 'candy'

Cars : [Audi, BMW, Mercedes, Nissan, Volvo]
Size : 5
Is Empty: false
Is Empty: true


In the following example, we will use for-each loop to iterate over a TreeSet.


import java.util.TreeSet;

public class IterateTreeSetUsingSimpleForEachLoop {
    public static void main(String[] args) {
        TreeSet<String> cars = new TreeSet<>();

        cars.add("BMW");
        cars.add("Volvo");
        cars.add("Audi");
        cars.add("Mercedes");
        cars.add("Nissan");

        for (String car : cars) {
            System.out.println("Car : " + car);
        }
    }
}


Output:


$ javac IterateTreeSetUsingSimpleForEachLoop.java
$ java IterateTreeSetUsingSimpleForEachLoop
Car : Audi
Car : BMW
Car : Mercedes
Car : Nissan
Car : Volvo


The following example shows how to iterate over TreeSet elements using Iterator.


import java.util.TreeSet;
import java.util.Iterator;

public class TreeSetIteratorExample {
    public static void main(String[] args) {
        TreeSet<String> cars = new TreeSet<>();

        cars.add("BMW");
        cars.add("Volvo");
        cars.add("Audi");
        cars.add("Mercedes");
        cars.add("Nissan");

        Iterator<String> carItr = cars.iterator();
        while(carItr.hasNext()) {
            String car = carItr.next();
            System.out.println("Car: " + car);
        }
    }
}

Output:


$ javac TreeSetIteratorExample.java
$ java TreeSetIteratorExample
Car: Audi
Car: BMW
Car: Mercedes
Car: Nissan
Car: Volvo


The following example shows how to create a TreeSet using custom objects.


import java.util.Objects;
import java.util.TreeSet;
import java.util.SortedSet;

class Car implements Comparable{
    private int id;
    private String name;
    private String model;

    public Car(int id, String name, String model) {
        this.id = id;
        this.name = name;
        this.model = model;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Car car = (Car) o;
        return id == car.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public int compareTo(Car car) {
        return this.getId() - car.getId();
    }

    @Override
    public String toString() {
        return String.format(
            "Car{name='%s', model='%s'}",
            name, model);
    }
}

public class TreeSetCustomObjectsExample {
    public static void main(String[] args) {
        TreeSet<String> cars = new TreeSet<>();
        cars.add(new Car(1,"BMW", "520"));
        cars.add(new Car(100,"Volvo", "V90"));
        cars.add(new Car(3, "Nissan", "Qashqa"));
        cars.add(new Car(19,"Mercedes-Benz", "CLA 200"));

        System.out.println("Cars : " + cars);

        // iterate using for-each loop
        for (Car car : cars) {
            System.out.println("Car : " + car.getName() + " model: " + car.getModel());
        }
    }
}


Like you see the Car object implements Comparable interface because TreeSet needs to keep the objects sorted.
equals() methods checks if the Car objects are equal.
compareTo() method compare cars objects based on their Id's

Output:


$ javac TreeSetCustomObjectsExample.java
$ java TreeSetCustomObjectsExample
Cars : [Car{name='BMW', model='520'}, Car{name='Nissan', model='Qashqa'}, Car{name='Mercedes-Benz', model='CLA 200'}, Car{name='Volvo', model='V90'}]
Car : BMW model: 520
Car : Nissan model: Qashqa
Car : Mercedes-Benz model: CLA 200
Car : Volvo model: V90


Share this: