In this tutorials, we are going to learn what is TreeSet in Java and how to apply customized sorting on TreeSet. TreeSet in java is the implementation of the NavigableSet. The underlying data structure for TreeSet is Balanced Tree.

Since it is a Set, it doesn’t allow the duplicate values and insertion order is not preserved.  But all Objects which are inserted in the tree set are stored according to the some default sorting order, that is in the case of numbers ascending and in the case of strings alphabetical orders.

Constructors Available in TreeSet

TreeSet();

It creates an empty TreeSet, where elements will be inserted according to default sorting order.

TreeSet(Comparator c);

It Creates an empty TreeSet, where the elements will be inserted according to the customized sorting Order.

TreeSet(Collection c);

It creates an empty TreeSet, containing the elements with the given collection.

TreeSet(SortedSet c);

It creates an empty TreeSet, containing the elements with sorting order with the given SortedSet.

Key Points

  1. The underlying data structure for TreeSet is Balanced Tree.
  2. Since it is a Set implementation, duplicates are not allowed.
  3. Tree Set doesn’t maintain Insertion order.
  4. Tree Set allows the default sorting order.
  5. When we deal with the customize Sorting using TreeSet(Comparator c) constructor, the class should be implements Comparator interface.
  6. Though the Java collection framework allows the heterogeneous objects, but the TreeSet doesn’t allow  heterogeneous elements.
  7. We can not insert null values into TreeSet.

Example for TreeSet

TreeSetDemo.java
import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {   
    public static void main(String[] args) {       
        Set set = new TreeSet();       
        set.add("A");       
        set.add("M");       
        set.add("b");       
        set.add("Q");       
        set.add("P");       
        set.add("a");       
        System.out.println("Tree : " + set);   
    }
}

Output

Tree : [A, M, P, Q, a, b]

 

On the above, we can see the output with the default sorting order.

TreeSet doesn’t allow heterogeneous Elements

Example

TreeSetDemo.java
import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {
    public static void main(String[] args) {
        Set set = new TreeSet();
        set.add("A");
        set.add("M");
        set.add("b");
        set.add(4);
        set.add(1);
        set.add(9);
        System.out.println("Tree : "+set);
    }
}

Output:

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer.

If we try to insert the different objects on single Tree Set, we can get the ClassCastException

Customized Sorting Example

Here is the example for Customized sorting on TreeSet.

TreeComparatorDemo.java
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

/**
 *
 * @author chandrashekhar
 */
public class TreeComparatorDemo {

       
    public static void main(String[] args) {       
        Set set = new TreeSet(new CityComparator());       
        set.add(new City(1, "Vijayawada"));       
        set.add(new City(5, "Mumbai"));       
        set.add(new City(4, "Visakhapatnam"));       
        set.add(new City(2, "Delhi"));       
        System.out.println("Tree : " + set);   
    }
}

class City {
       
    int id;   
    String city;
       
    public City(int id, String city) {       
        this.id = id;       
        this.city = city;   
    }
       
    @Override    public String toString() {       
        return "City{" + "id=" + id + ", city=" + city + '}';   
    }
}

class CityComparator implements Comparator < City > {

    @Override    public int compare(City o1, City o2) {       
        if (o1.id == o2.id) {           
            return 0;       
        } else if (o1.id > o2.id) {           
            return 1;       
        } else {           
            return -1;       
        }   
    }
}

Output:

Tree : [City{id=1, city=Vijayawada}, City{id=2, city=Delhi}, City{id=4, city=Visakhapatnam}, City{id=5, city=Mumbai}]

Happy Learning 🙂

Leave A Comment