TreeMap(Comparator comp)

In this post, we will see how to use a comparator in TreeMap and also see the treemap comparator example. If you are a beginner and you are not familiar with Comparator and TreeMap then I recommend you please read them first.(TreeMap(Comparator comp))

As we know TreeMap maintains the order of keys, by default it maintains the ascending order of keys. But there may a situation when you don’t want to sort the TreeMap in ascending order and you want to sort a TreeMap sort by value.

To achieve this task we will use the parameterized constructor of TreeMap that takes Comparator as input and maintain the order. So let’s have a look at the constructor:

TreeMap(Comparator comp) & Treemap sort by value

This constructor takes a parameter of Comparator type and returns the object of TreeMap that will maintain the order of objects. It returns an empty object of TreeMap but when we will add elements in the object it will maintain the order.

TreeMap<K,V> NameOfTreeMap =  new TreeMap <K,V>(Comparator <? super E> comparator);

Here, K denotes the type of key in TreeMap, and V denotes the type of Value in TreeMap.
comparator, It’s the argument of Comparator type, it means it will hold the object of a comparator.

TreeMap<Integer, String> NameOfTreeMap =  new TreeMap< Integer, String >(comparator);

Let’s take an example TreeMap sorting and see how to use TreeMap comparator by value.
Suppose you have an Employee class and you want to sort the data of Employee based on requirements like sorting by names, employee’s code etc. To acheive this task we have to perform some steps.

Steps to sort a TreeMap with a Comparator

Step 1: Create the Employee class that will contain employee’s information.

Step 2: Create the Comparators that you want to use the for sorting the data.

Step 3: When we will create a TreeMap we need to provide a comparator that will used in sorting of TreeMap.

import java.util.Comparator;
import java.util.TreeMap;
class Employee
{
    private String name;
    private int salary;
    private int empCode;
    public Employee(String name, int salary, int empCode) {
		this.name = name;
		this.salary = salary;
		this.empCode = empCode;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getSalary() {
		return salary;
	}
	public void setSalary(int salary) {
		this.salary = salary;
	}
	public int getEmpCode() {
		return empCode;
	}
	public void setEmpCode(int empCode) {
		this.empCode = empCode;
	}
	public String toString(){
        return "Name: "+this.name+" and Salary: "+this.salary+" and Code: "+ this.empCode;
    }
}
// Creating a comparator for Employee's name
class EmpName implements Comparator<Employee>{
    @Override
    public int compare(Employee e1, Employee e2) {
        return e1.getName().compareTo(e2.getName());
    }
}
//Creating a comparator for Employee's Salary
class EmpSalary implements Comparator<Employee>{
    @Override
    public int compare(Employee e1, Employee e2) {
        if(e1.getSalary() > e2.getSalary()){
            return 1;
        } else {
            return -1;
        }
    }
}
//Creating a comparator for employee's Code
class EmpCode implements Comparator<Employee>{
    @Override
    public int compare(Employee e1, Employee e2) {
        if(e1.getEmpCode() > e2.getEmpCode()){
            return 1;
        } else {
            return -1;
        }
    }
}
public class TreeMapSorting {
    public static void main(String a[])
    {
        // Here we are using a comparator that will sort based on names
        TreeMap<Employee,String> treeMapSortName = new TreeMap<Employee, String>(new EmpName());
        treeMapSortName.put(new Employee("Ram", 30000, 101), "A");
        treeMapSortName.put(new Employee("Sham", 60000, 105), "B");
        treeMapSortName.put(new Employee("Krishna", 15000, 102), "C");
        treeMapSortName.put(new Employee("Radhe", 24000, 103), "D");
        treeMapSortName.put(new Employee("Ravi", 7000, 110), "E");
        System.out.println("Sorting based on names: ");
        for(Employee key : treeMapSortName.keySet())
        {
            System.out.println(key);
        }
        System.out.println("=============================================");
        // Here we are using a comparator that will sort based on salary
        TreeMap<Employee,String> treeMapSortSalary = new TreeMap<Employee, String>(new EmpSalary());
        treeMapSortSalary.put(new Employee("Ram", 30000, 101), "A");
        treeMapSortSalary.put(new Employee("Sham", 60000, 105), "B");
        treeMapSortSalary.put(new Employee("Krishna", 15000, 102), "C");
        treeMapSortSalary.put(new Employee("Radhe", 24000, 103), "D");
        treeMapSortSalary.put(new Employee("Ravi", 7000, 110), "E");
        System.out.println("Sorting based on salary: ");
        for(Employee key:  treeMapSortSalary.keySet())
        {
            System.out.println(key);
        }
        System.out.println("=============================================");
        // Here we are using a comparator that will sort based on employee code
        TreeMap<Employee,String> treeMapSortEmpCode = new TreeMap<Employee, String>(new EmpCode());
        treeMapSortEmpCode.put(new Employee("Ram", 30000, 101), "A");
        treeMapSortEmpCode.put(new Employee("Sham", 60000, 105), "B");
        treeMapSortEmpCode.put(new Employee("Krishna", 15000, 102), "C");
        treeMapSortEmpCode.put(new Employee("Radhe", 24000, 103), "D");
        treeMapSortEmpCode.put(new Employee("Ravi", 7000, 110), "E");
        System.out.println("Sorting based on Employee code: ");
        for(Employee key:  treeMapSortEmpCode.keySet())
        {
            System.out.println(key);
        }
    }
}

Output: Sorting based on names:
Name: Krishna and Salary: 15000 and Code: 102 ==> C
Name: Radhe and Salary: 24000 and Code: 103 ==> D
Name: Ram and Salary: 30000 and Code: 101 ==> A
Name: Ravi and Salary: 7000 and Code: 110 ==> E
Name: Sham and Salary: 60000 and Code: 105 ==> B

Sorting based on salary:
Name: Ravi and Salary: 7000 and Code: 110 ==> null
Name: Krishna and Salary: 15000 and Code: 102 ==> null
Name: Radhe and Salary: 24000 and Code: 103 ==> null
Name: Ram and Salary: 30000 and Code: 101 ==> null
Name: Sham and Salary: 60000 and Code: 105 ==> null

Sorting based on Employee code:
Name: Ram and Salary: 30000 and Code: 101 ==> null
Name: Krishna and Salary: 15000 and Code: 102 ==> null
Name: Radhe and Salary: 24000 and Code: 103 ==> null
Name: Sham and Salary: 60000 and Code: 105 ==> null
Name: Ravi and Salary: 7000 and Code: 110 ==> null

Frequently Asked Questions

What does the TreeMap(Comparator comp) constructor do?

It creates an empty TreeMap that will maintain the order of its keys according to the Comparator you pass in. When you add elements, the TreeMap uses that Comparator to keep the keys sorted instead of using their natural ordering.

How do I sort a TreeMap by value?

TreeMap orders its keys, not its values. To sort by value you supply a Comparator through the TreeMap(Comparator comp) constructor that compares the keys based on the value you care about — as shown in the Employee example on this page, where separate comparators sort by name, salary, and employee code.

What is the difference between natural ordering and a Comparator in TreeMap?

By default a TreeMap keeps keys in ascending natural order. When you pass a Comparator to the constructor, that Comparator takes over and decides the ordering, so you can sort by any field or rule you define.

Can I use more than one Comparator with the same TreeMap?

Each TreeMap instance is created with one Comparator. To sort the same data in different ways, create separate TreeMap instances, each constructed with the Comparator you need — exactly as the example creates treeMapSortName, treeMapSortSalary, and treeMapSortEmpCode.

Do I need to know Comparator and TreeMap before reading this page?

Yes. The page recommends reading the Comparator interface and TreeMap tutorials first if you are a beginner, since this article builds directly on those concepts.

Leave a Comment