How to Sort a TreeSet with User Defined Objects in Java?
Last Updated :
08 Feb, 2022
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
Similar Reads
How to Avoid Duplicate User Defined Objects in TreeSet in Java? TreeSet class in Java is part of Javaâs collections framework which implements the NavigableSet interface, which provides functionalities to navigate through the SortedSet. The NavigableSet further extends the SortedSet interface, which provides functionalities to keep the elements sorted. As the Tr
5 min read
Creating TreeSet with Comparator by User Define Objects in Java TreeSet is the implementation class of Set Interface. It follows a natural sorting order or you can customize it using a comparator and it also does not allow duplicates. Syntax: TreeSet<String> gfg= new TreeSet<>(); Below is the normal implementation of the TreeSet: Java // Java program
6 min read
How to Create a TreeSet with a List in Java? TreeSet is an implementation of the SortedSet interface in Java that uses a Tree for storage. TreeSet can be created from List by passing the List to the TreeSet constructor in Java or we can traverse complete List and adding each element of the List to the TreeSet. Example: Input : List = [a, b, c]
3 min read
Java Program to Sort Keys in TreeMap by using Comparator with User Defined Objects The TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. To sort keys in TreeMap by using a comp
3 min read
How to sort TreeSet in descending order in Java? Given a TreeSet in Java, task is to sort elements of TreeSet in Descending Order (descreasing order).Examples: Input : Set: [2, 3, 5, 7, 10, 20] Output : Set: [20, 10, 7, 5, 3, 2] Input : Set: [computer, for, geeks, hello] Output : Set: [hello, geeks, for, computer] Approach: To make a TreeSet Eleme
1 min read
How to Add Custom Class Objects to the TreeSet in Java? TreeSet is an implementation of the SortedSet interface in java that uses a red-black tree for storage. By default, It maintains an ascending order. It contains unique elements only. It doesn't allow null elements. Access and retrieval times are quite fast. To add the user-defined object into TreeSe
3 min read