Thursday, 7 December 2017

Example to sort keys of TreeMap using Comparator with Custom Object

        In the below code, we are passing custom object as key in TreeMap i.e Employee user defined class. In this case, we need to pass the comparator object in the constructor, while creating the TreeMap object.  In the Comparator, need to override the compare method and to write the sorting logic.

 Example:--

package com.test;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class TreeMapSorting { 
 
     public static void main(String[] args) { 
 
           TreeMap<Employee, String> treeMap = new TreeMap<Employee, String>(new MyNameComp()); 
 
           treeMap.put(new Employee(10,  "Anil"), "one");
           treeMap.put(new Employee(10,  "Mahesh"), "two");
           treeMap.put(new Employee(10,  "John"), "three");
           treeMap.put(new Employee(10,  "Nagesh"), "four");
           for (Map.Entry<Employee, String> map : treeMap.entrySet()) {
                 System.out.println("Key : ("+map.getKey()+ "), Value : "+ map.getValue());
           }
     }
}
 
class Employee { 
 
     private Integer id;
     private String name; 
 
     public Employee(Integer id, String name) {
          this.id = id;
          this.name = name;
     }
     public Integer getId() {
          return id;
     }
     public void setId(Integer id) {
          this.id = id;
     }
     public String getName() {
          return name;
     }
     public void setName(String name) {
          this.name = name;
     }
     public String toString() {
          return this.name+":"+id;
     }
}

class MyNameComp implements Comparator<Employee> {

     public int compare(Employee o1, Employee o2) {
            return o1.getName().compareTo(o2.getName());
     }
 
}

Output : -Key : (Anil:10), Value : one
               Key : (John:10), Value : three
              Key : (Mahesh:10), Value : two
              Key : (Nagesh:10), Value : four



Related Post :--
How to iterate the TreeMap in reverse order in Java  
Internal Implementation of TreeMap in Java  
Internal Implementation of LinkedList in Java  
Internal implementation of ArrayList in Java  
How HashMap works internally in Java?  

1 comment:

  1. I really appreciate the information shared above. It’s of great help. If someone wants to learn Online (Virtual) instructor lead live training in #ALFRESCO, kindly contact us http://www.maxmunus.com/contact
    MaxMunus Offer World Class Virtual Instructor-led training on #ALFRESCO. We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ pieces of training in India, USA, UK, Australia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain, and UAE etc.
    Avishek Priyadarshi
    MaxMunus
    E-mail: avishek@maxmunus.com
    Skype id: avishek_2.
    Ph:(0) 8553177744 / 080 - 41103383
    http://www.maxmunus.com/

    ReplyDelete