Topics Index

TreeSetCustomSortingDemo - Java Example Program

import java.util.*;

class TreeSetCustomSortingDemo
    public static void main(String arg[])
        TreeSet<Student> students = new TreeSet<Student>(); // LINE B
        students.add(new Student("Sreeram", 10, 'A'));
        students.add(new Student("Karthik", 12, 'A'));
        students.add(new Student("Ram", 14, 'B'));
        students.add(new Student("Yeshwanthi", 5, 'C'));
        students.add(new Student("Bhavya", 6, 'D'));
        System.out.println(students); // LINE C
        TreeSet newStudents = (TreeSet) students.clone();

class Student implements Comparable<Student>
    String name;
    int rollNumber;
    char section;
    public Student(String name, int rollNumber, char section)
    { = name;
        this.rollNumber = rollNumber;
        this.section = section;
    public String toString()
        return name + " " + rollNumber + " " + section;
    public int compareTo(Student o)
        return rollNumber - o.rollNumber;

[Yeshwanthi 5 C, Bhavya 6 D, Sreeram 10 A, Karthik 12 A, Ram 14 B]


In the above program we have demonstrated how to change the natural ordering of the TreeSet depending on the requirements. Firstly we have created a Student class which implements Comparable interface with the fields name, rollNumber, section and implemented toString and compareTo method of Comparable interface. At LINE B in the other class we have created a TreeSet and added Student objects. Now Set will consider the compareTo method in the Student class and sorts the objects accordingly.

  • Now sort the elements with respect to section. Use the below sample code.
    return rollNumber - o.rollNumber;
  • Create a clone for the above set using clone method. Use the below sample code.
    TreeSet newStudents = (TreeSet) students.clone();
    In the above code we type casted to TreeSet since the return type of clone is Object a Type mismatch exception may raise otherwise.

© meritcampus 2019

All Rights Reserved.

Open In App