Sort values in HashMap by using Comparator with user defined objects

52 Views Asked by At

I have a HashMap as follows:

public class MyHashMapOfEmployees {

  public static void main(String a[]){
    Map<String,Employee> allEmployees= new HashMap<String,Employee>();
    allEmployees.put(new Employee("111",("Ram", "Smith", "developer"));
    allEmployees.put(new Employee("222",("John", "Doe", "manager"));
    allEmployees.put(new Employee("333",("Lisa", "Hart", "CEO"));
    allEmployees.put(new Employee("444",("Mark", "Wayman", "VP"));
  }
}

Here is my Employee class:

class Employee{    

private String firstName;
private String lastName;
private String position;
private String id;

public Employee(String fn, String ln, String p){
    this.firstName = fn;
    this.lastName = ln;
    this.position = p;
}     
public String getFirstName() {
    return firstName;
}
public String getLastName() {
    return lastName;
}
public String getPosition() {
    return position;
}
public String getId() {
    return id;
}

}

I need to sort my HashMap by employees first name, and keys (id) can be omitted. Final output should be as follows:

John Doe manager
Lisa Hart CEO
Mark Wayman VP
Ram Smith developer

I tried using the following comparator:

private final Comparator<Employee> employeeComparator = new Comparator<Employee>() {
    @Override
    public int compare(Employee o1, Employee o2) {
        return o1.getFirstName().compareTo(o2.getFirstName());
    }
};

How can I sort this HashMap not by the value (which in my case is an object - Employee), but by a particular field in my object (firstName)?

Is TreeMap not the right solution?

I've searched through stackOverflow and there is nothing for this particular scenario that I could apply and get to work. THIS ISN'T A DUPLICATE, the link that is being offered in comments is a different task.

Can I do the following without creating a TreeMap in between?

SortedSet<Map.Entry<String, Employee>> employeesSortedByFirstName = new TreeSet<Map.Entry<String, Employee>>(employeeComparator()); 

employeesSortedByFirstName.addAll(allEmployees.entrySet());

Would this sort my map values by first name?... or by the order of insertion?..

OR - do I need a TreeMap in between as such:

SortedSet<Map.Entry<String, Employee>> employeesSortedByFirstName = new TreeSet<Map.Entry<String, Employee>>(employeeComparator());

SortedMap<String, Employee> sortedMap = new TreeMap<String, Employee>();
sortedMap.putAll(allEmployees); //hashmap into treemap
employeesSortedByFirstName.addAll(sortedMap.entrySet()); //add treemap into the sorted set

THE GOAL IS TO SORT BY FIRST NAME, NOT BY THE WHOLE VALUE OF THE MAP.

0

There are 0 best solutions below