Skip to content
Related Articles

Related Articles

Improve Article

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);
        }
    }
}
Output
fifth
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;
    }
}
Output
Sorting 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;
    }
}
Output
Sorting 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

 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :