Search code examples
javacollectionscomparatortreemap

How to write my own comparator class in java?


I didn't find proper solution for the below scenario. I have employee names and location. In each location many employees can work. Example: assume that employee names are unique so I consider it as a key and value as location.

TreeMap<String,String> t=new TreeMap<String,String>();
t.put(mike, Houston);
t.put(arian, Houston);
t.put(John, Atlanta);

Well my scenario is i have to write my own comparator where location is sorted first and when there are multiple locations of same name then they need to be sorted by employees. Any kind of help is appreciated.


Solution

  • you need a structure, and compareTo:

    public class EmpLoc  implements Comparable<EmpLoc>  {
    String employee;
    String location;
    
    public EmpLoc (String _employee, String _location)
        {
        employee=_employee;
        location=_location; 
        }
    
    
    @Override
    public int compareTo(EmpLoc other)
        {
        int last = this.location.compareTo(other.location);
        return last == 0 ? this.employee.compareTo(other.employee) : last;
        }
    
    }