Creating TreeSet with Comparator by User Define Objects in Java
Last Updated :
17 May, 2021
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 for TreeSet
import java.io.*;
import java.util.TreeSet;
class GFG {
public static void main(String[] args)
{
TreeSet<String> gfg = new TreeSet<String>();
// adding elements in Treeset using add() method
gfg.add("first");
gfg.add("second");
gfg.add("third");
gfg.add("fourth");
gfg.add("fifth");
// iterating over the TreeSet using
// foreach loop and printing it
for (String value : gfg) {
System.out.println(value);
}
}
}
Outputfifth
first
fourth
second
third
Creating TreeSet with Comparator for user-defined Objects
1. Using Interfaces for making a comparator object :
First, we will create one Employee class having attributes age, id, name and one default constructor and one parameterized constructor. Now we need to create the Comparator classes implementing comparator interface and need to override the compare() method. The return type for the comparator method is an integer(1, -1, 0).
For example Objects as (Object o1, Object o2)
For ascending order (Integers)
if(o1<o2) return -1;
else if(o1>o2) return +1;
else return 0;
For descending order (Integers)
if(o1<o2) return +1;
else if(o1>o2) return -1;
else return 0;
For strings in ascending order
return s1.compareTo(s2); //here s1 , s2 are strings
For strings in descending order
return -s1.compareTo(s2);//here s1 , s2 are strings
Now we will create a TreeSet of employees and employee into it and in the constructor, we need to pass the comparator object
Syntax :
TreeSet<Employees> gfg=new TreeSet<>(comparatorObject);
gfg.add(new Employee(1,"raja",23);
Below is the implementation of the above problem statement:
Java
// Java program for treeset of user
// defined objects and using comparator
import java.io.*;
import java.util.Comparator;
import java.util.TreeSet;
class GFG {
public static void main(String[] args)
{
// TreeSet of user defined objects
// and using comparator also
// we will create TreeSet of employees
System.out.println(
"Sorting on the basis of name in Ascending order");
// passed first comparator object for
// sorting in ascending order of name
TreeSet<Employee> gfg
= new TreeSet<>(new FirstComparator());
gfg.add(new Employee(1, "ram", 24));
gfg.add(new Employee(2, "krishna", 23));
gfg.add(new Employee(3, "sita", 26));
gfg.add(new Employee(4, "lakshman", 25));
// printing each employee object
for (Employee employee : gfg) {
System.out.println(employee);
}
System.out.println(
"Sorting on the basis of name in Descending order");
// Passed second comparator object for
// Sorting in descending order of name
TreeSet<Employee> gfg2
= new TreeSet<>(new SecondComparator());
gfg2.add(new Employee(1, "ram", 24));
gfg2.add(new Employee(2, "krishna", 23));
gfg2.add(new Employee(3, "sita", 26));
gfg2.add(new Employee(4, "lakshman", 25));
// printing each employee object
for (Employee employee : gfg2) {
System.out.println(employee);
}
// ThirdComparator
System.out.println(
"Sorting on the basis of age in ascending order");
TreeSet<Employee> gfg3
= new TreeSet<>(new ThirdComparator());
gfg3.add(new Employee(1, "ram", 24));
gfg3.add(new Employee(2, "krishna", 23));
gfg3.add(new Employee(3, "sita", 26));
gfg3.add(new Employee(4, "lakshman", 25));
// printing each employee object
for (Employee employee : gfg3) {
System.out.println(employee);
}
}
}
// for sorting in ascending order
class FirstComparator implements Comparator<Employee> {
@Override public int compare(Employee e1, Employee e2)
{
return (e1.name).compareTo(e2.name);
}
}
// for sorting in descending order
// passed in reverse order e2 first than e1
class SecondComparator implements Comparator<Employee> {
@Override public int compare(Employee e1, Employee e2)
{
return -(e1.name).compareTo(e2.name);
}
}
// Sorted on the basis of age
class ThirdComparator implements Comparator<Employee> {
@Override public int compare(Employee e1, Employee e2)
{
if (e1.age > e2.age) {
return -1;
}
else if (e1.age < e2.age) {
return 1;
}
else {
return (e1.age).compareTo(e2.age);
}
}
}
// Employee class
class Employee {
// Employee has three attributes
// id , name, age
public int id;
public String name;
public Integer age;
// default constructor
Employee() {}
// parameterized constructor
Employee(int id, String name, int age)
{
this.id = id;
this.name = name;
this.age = age;
}
@Override public String toString()
{
return "" + this.id + " " + this.name + " "
+ this.age;
}
}
OutputSorting on the basis of name in Ascending order
2 krishna 23
4 lakshman 25
1 ram 24
3 sita 26
Sorting on the basis of name in Descending order
3 sita 26
1 ram 24
4 lakshman 25
2 krishna 23
Sorting on the basis of age in ascending order
3 sita 26
4 lakshman 25
1 ram 24
2 krishna 23
2. Using java 8 lambda expression:
Here we will not create the separate classes which will implement the comparator interface and hence no need to override the compare method. Now we simply need to use the lambda expressions directly into the constructor of TreeSet rest of things are the same only difference here we are using lambda for comparator object
Syntax :
TreeSet<Employee> gfg2=new TreeSet<>(
(Employee e1 , Employee e2)->e1.name.compareTo(e2.name));
Below is the implementation of the problem statement:
Java
// Java program for treeset of user
// defined objects and using comparator
import java.io.*;
import java.util.Comparator;
import java.util.TreeSet;
class GFG {
public static void main(String[] args)
{
// TreeSet of user defined objects
// we will create TreeSet of employees
System.out.println(
"Sorting on the basis of name ascending order");
// passing comparator using lambda expressions
TreeSet<Employee> gfg
= new TreeSet<>((Employee e1, Employee e2)
->
- (e1.name).compareTo(e2.name));
gfg.add(new Employee(1, "ram", 24));
gfg.add(new Employee(2, "krishna", 23));
gfg.add(new Employee(3, "sita", 26));
gfg.add(new Employee(4, "lakshman", 25));
for (Employee employee : gfg) {
System.out.println(employee);
}
// SecondComparator
System.out.println(
"Sorting on the basis of name ascending order");
TreeSet<Employee> gfg2 = new TreeSet<>(
(Employee e1,
Employee e2) -> e1.name.compareTo(e2.name));
// adding employee object to treeSet
gfg2.add(new Employee(1, "ram", 24));
gfg2.add(new Employee(2, "krishna", 23));
gfg2.add(new Employee(3, "sita", 26));
gfg2.add(new Employee(4, "lakshman", 25));
// printing every employee object
for (Employee employee : gfg2) {
System.out.println(employee);
}
}
}
class Employee {
// Employee has three attributes
// id , name, age
public int id;
public String name;
public Integer age;
// default constructor
Employee() {}
// parameterized constructor
Employee(int id, String name, int age)
{
this.id = id;
this.name = name;
this.age = age;
}
@Override public String toString()
{
return "" + this.id + " " + this.name + " "
+ this.age;
}
}
OutputSorting on the basis of name ascending order
3 sita 26
1 ram 24
4 lakshman 25
2 krishna 23
Sorting on the basis of name ascending order
2 krishna 23
4 lakshman 25
1 ram 24
3 sita 26
Similar Reads
How to Sort a TreeSet with User Defined Objects in Java?
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 Tree
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 Create TreeMap Objects using Comparable Interface in Java?
In Java, the TreeMap class is an implementation of the SortedMap interface that stores key-value pairs in a sorted order based on the natural ordering of the keys. By default, the keys are sorted in ascending order. If you want to sort the keys based on a custom ordering criteria, you can use the Co
6 min read
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
Sort ArrayList in Descending Order Using Comparator in Java
A comparator is an interface that is used to rearrange the ArrayList in a sorted manner. A comparator is used to sort an ArrayList of User-defined objects. In java, a Comparator is provided in java.util package. Using Comparator sort ArrayList on the basis of multiple variables, or simply implement
3 min read
Get Two Different Objects Into a TreeSet in Java
In Java, TreeSet is a part of the Java Collection Framework and is located in the java.util package. It implements the NavigableSet interface and extends the AbstractSet and TreeSet is known for maintaining its elements in sorted order, either based on their natural order. This must be consistent wi
3 min read
Creating a User-Defined Printable Pair Class in Java
The pair class in C++ Standard Library is used a lot. We can implement our own user-defined pair class in Java and its object can be used anywhere just like any other parameter. Note : This class is equivalent to pair<int,int> class in java. You can create your own template or classes for othe
3 min read
Sort Java Vector in Descending Order Using Comparator
The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in java.util package and implements the List interface, so we can use all the methods of the List interface. There are two types of Sorting t
3 min read
How to Compare Two TreeMap Objects in Java?
TreeMap class in java provides a way of storing key-value pairs in sorted order. The below example shows how to compare two TreeMap objects using the equals() method. It compares two TreeMap objects and returns true if both of the maps have the same mappings else returns false. Syntax: boolean equal
1 min read
Creating and Populating a TreeSet in Java
In Java, TreeSet is a pre-defined class that can be used to implement the Set interface and it is a part of the Java collection framework TreeSet is a NavigableSet implementation based on the TreeMap. TreeSet follows the natural order which means elements can be stored in sorted order and it cannot
2 min read