Open In App

How to Sort a TreeSet with User Defined Objects in Java?

Last Updated : 08 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Comparator interface sorts the objects of user-defined classes. An object of the Comparator class is capable of comparing two objects of two different classes. Following function compare obj1 with obj2

  • TreeSet implements the SortedSet interface. So, duplicate values are not allowed.
  • Objects in a TreeSet are stored in a sorted and ascending order.
  • TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
  • If we are depending on the default natural sorting order, the objects that are being inserted into the tree should be homogeneous and comparable. TreeSet does not allow inserting Heterogeneous objects. It will throw a classCastException

Since TreeSet implements the sortedSet interface, therefore, the elements by default are sorted in ascending order. But if we want to change in the Sorting like to make it in decreasing order or sorting on the basis of name, marks, Salary (these all are user-defined classes) like in any ways.

So the solution to all this that we can do the sorting by implementing the comparator class Explicitly.

Syntax:

public int compare(Object obj1, Object obj2):

Approach :

  • Comparator interface is used to order the objects of the user-defined class.
  • This interface is present in java.util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element).
  • Using a comparator, we can sort the elements based on data members. For instance, it may be on marks, name, or anything else.

Method of Collections class for sorting List elements is used to sort the elements of List by the given comparator. 

// To sort a given list. ComparatorClass must implement 
// Comparator interface.

public void sort(List list, ComparatorClass c)

Example:

Java




// Java program to Sort a TreeSet with
// User Defined Objects
 
import java.io.*;
import java.util.*;
class students{
   
    private int marks;
    private String name;
   
    // constructor
    public students(int value, String name)
    {
        this.marks=value;
        this.name=name;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name= name;
    }
     
    public int getMarks()
    {
        return marks;
    }
     
}
 
// Comparator class will override the compare
// method which will compare the two objects
// passed in the parameter
class myMarksComparator implements Comparator<students>
{
   
    public int compare(students s1, students s2)
    {
        return s1.getMarks()-s2.getMarks();
    }
}
 
class myNameComparator implements Comparator<students>
{
    public int compare(students s1, students s2)
    {
        return s1.getName().compareTo(s2.getName());
    }
}
 
class GFG {
 
    public static void main (String[] args){
         
        // Creating the TreeSet with Comparator object passed
        // as the parameter which will sort the user defined
        // objects of TreeSet
        TreeSet<students> set = new TreeSet<students>(new myMarksComparator());
         
        set.add(new students(450,"Sam"));
        set.add(new students(341,"Ronaldo"));
        set.add(new students(134,"Daniel"));
        set.add(new students(590,"George"));
         
        System.out.println("increasing Order with the Marks");
         
        // Printing the TreeSet elements
        for(students ele: set)
        {
            System.out.print(ele.getName()+" "+ele.getMarks());
            System.out.println();
        }
         
         
        TreeSet<students> mrks= new TreeSet<students>(new myNameComparator());
         
        mrks.add(new students(450,"Sam"));
        mrks.add(new students(341,"Ronaldo"));
        mrks.add(new students(134,"Daniel"));
        mrks.add(new students(590,"George"));
         
        System.out.println();
         
        for(students ele : mrks)
        {
            System.out.print(ele.getName() +" "+ ele.getMarks());
            System.out.println();
        }
 
    }
}


Output

-------increasing Order with the Marks
Daniel 134
Ronaldo 341
Sam 450
George 590

Daniel 134
George 590
Ronaldo 341
Sam 450


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads