TreeSet with Customizable Sorting in Java - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
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.
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.

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

The underlying data structure for TreeSet is Balanced Tree.
Since it is a Set implementation, duplicates are not allowed.
Tree Set doesn’t maintain Insertion order.
Tree Set allows the default sorting order.
When we deal with the customize Sorting using TreeSet(Comparator c) constructor, the class should be implements Comparator interface.
Though the Java collection framework allows the heterogeneous objects, but the TreeSet doesn’t allow  heterogeneous elements.
We can not insert null values into TreeSet.
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.
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
Here is the example for Customized sorting on TreeSet.
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 🙂

Comparator in Java
Java 8 how to remove duplicates from list
Bubble Sort In Java
Difference between HashSet vs TreeSet in Java
Comparator vs Comparable in Java
How to Sort ArrayList in Java Ascending Order
Comparable in Java
How to Sort ArrayList in Java Descending Order
String sorting in Java
Java Program for String Sorting Example
User defined sorting with Java 8 Comparator
HashSet In Java in Java Example
How HashMap Works In Java
LinkedHashSet in Java
ArrayList in Java

Comparator in Java
Java 8 how to remove duplicates from list
Bubble Sort In Java
Difference between HashSet vs TreeSet in Java
Comparator vs Comparable in Java
How to Sort ArrayList in Java Ascending Order
Comparable in Java
How to Sort ArrayList in Java Descending Order
String sorting in Java
Java Program for String Sorting Example
User defined sorting with Java 8 Comparator
HashSet In Java in Java Example
How HashMap Works In Java
LinkedHashSet in Java
ArrayList in Java
 


Δ
 Install Java on Mac OS
 Install AWS CLI on Windows
 Install Minikube on Windows
 Install Docker Toolbox on Windows
 Install SOAPUI on Windows
 Install Gradle on Windows
 Install RabbitMQ on Windows
 Install PuTTY on windows
 Install Mysql on Windows
 Install Hibernate Tools in Eclipse
 Install Elasticsearch on Windows
 Install Maven on Windows
 Install Maven on Ubuntu
 Install Maven on Windows Command
 Add OJDBC jar to Maven Repository
 Install Ant on Windows
 Install RabbitMQ on Windows
 Install Apache Kafka on Ubuntu
 Install Apache Kafka on Windows
 Java8 – Install Windows
 Java8 – foreach
 Java8 – forEach with index
 Java8 – Stream Filter Objects
 Java8 – Comparator Userdefined
 Java8 – GroupingBy
 Java8 – SummingInt
 Java8 – walk ReadFiles
 Java8 – JAVA_HOME on Windows
 Howto – Install Java on Mac OS
 Howto – Convert Iterable to Stream
 Howto – Get common elements from two Lists
 Howto – Convert List to String
 Howto – Concatenate Arrays using Stream
 Howto – Remove duplicates from List
 Howto – Filter null values from Stream
 Howto – Convert List to Map
 Howto – Convert Stream to List
 Howto – Sort a Map
 Howto – Filter a Map
 Howto – Get Current UTC Time
 Howto – Verify an Array contains a specific value
 Howto – Convert ArrayList to Array
 Howto – Read File Line By Line
 Howto – Convert Date to LocalDate
 Howto – Merge Streams
 Howto – Resolve NullPointerException in toMap
 Howto -Get Stream count
 Howto – Get Min and Max values in a Stream
 Howto – Convert InputStream to String