Easy learning with example program codes

how to sort keys in treemap by using comparator?


TreeMap extends AbstractMap class and implements the NavigableMap interface. It contains the elements in key-value pair form. It maintains ascending order for its elements. It not allowed duplicate key.

Note: A TreeMap can have only one null key but can have multiple null values.


package com.codesjava;
import java.util.Comparator;
import java.util.TreeMap;
class Employee{    
    private String name;
    private int salary;
    private int id;
    public Employee(int id, String name, int salary){ = id; = name;
        this.salary = salary;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public int getSalary() {
        return salary;
    public void setSalary(int salary) {
        this.salary = salary;
    public int getId() {
	return id;
    public void setId(int id) { = id;
    public String toString(){
        return "Id: "", Name: "", Salary: "+this.salary;
class EmployeeComp implements Comparator<Employee>{	 
    public int compare(Employee e1, Employee e2) {
        if(e1.getId() == e2.getId()){
            return 0;
        } if(e1.getId() < e2.getId()){
            return 1;
        } else {
            return -1;
public class Test {
	public static void main(String args[]){
		TreeMap<Employee, String> treeMap = new TreeMap<Employee, String>(new EmployeeComp());
		treeMap.put(new Employee(1,"Jai",50000), "JAI");
		treeMap.put(new Employee(2,"Mahesh",80000), "MAHESH");
		treeMap.put(new Employee(3,"Vishal",60000), "VISHAL");
		treeMap.put(new Employee(4,"Hemant",64000), "HEMANT");


{Id: 4, Name: Hemant, Salary: 64000=HEMANT, Id: 3, 
Name: Vishal, Salary: 60000=VISHAL, Id: 2, Name: Mahesh, 
Salary: 80000=MAHESH, Id: 1, Name: Jai, Salary: 50000=JAI}

Copyright © 2018 CodesJava Protection Status SiteMap