0

I am creating one Hashmap object of key as Employee name and value as Employee object which has attribute as name, id & age. How to sort hashmap by value with employee's id?

MKumar
  • 79
  • 2
  • 6

4 Answers4

3

You can create a TreeMap instead of Hashmap.

Put the Employee id as the Key in the TreeMap and employee object as value.(Because you wanted to sort according to employee id and Employee id seems an unique for your context.)

TreeMap<Integer, EmpObj> map = new TreeMap<>();

If you can't change the map id, you can sort the hashmap by values. Refer to this link.

Ruchira
  • 115
  • 1
  • 2
  • 8
1

HashMaps are unorderd. Make your key as Id. And the map will be as follows,

Map<Integer, EmployeeDTO> map = new HashMap<>();

You can sort the map based on the key as follows,

SortedMap<Integer, EmployeeDTO> sortedMap = new TreeMap<Integer, EmployeeDTO>(map);

If you really need to keep name as key and sort by Id and if you are using java 8, can use following way,

Stream<Map.Entry<K,V>> sorted =
    map.entrySet().stream()
       .sorted(Map.Entry.comparingByValue(comparator));

Comparater you can create as,

public class EmployeeComparator implements Comparator<EmployeeDTO>{

    @Override
    public int compare(EmployeeDTO employeeDTO1, EmployeeDTO employeeDTO2) {

        try {
            if(employeeDTO1!=null && employeeDTO2!=null && 
                    employeeDTO1.getId()!=null && employeeDTO2.getId()!=null){
                try {
                    return Integer.parseInt(employeeDTO1.getId()) - Integer.parseInt(employeeDTO2.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }

}
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
0

Hashmap is not designed to be sorted. There is an interface SortedMap and one of its implementations - TreeMap, but it sorts the keys, not the values. So your result map will be sorted by employee name.

On the other hand, you may use LinkedHashMap and insert new values based on your rules, but I don't think that this is something you really want.

yateam
  • 119
  • 2
  • 9
0

yes you can sort by key. like other people suggest, you can use TreeMap to keep your keys sorted.

for example, this code will keep all elements sorted by its key:

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

public class Stack {

    public static void main(String args[]){

        TreeMap<Integer, String> map = new TreeMap<>();
        map.put(10,"Daniel");
        map.put(4,"Peter");
        map.put(1,"Claudia");

        for(Map.Entry<Integer,String> entry : map.entrySet()){
            System.out.println(entry.getKey() +" -> "+entry.getValue());
        }
        /* it will print to console:
        1 -> Claudia
        4 -> Peter
        10 -> Daniel 
        */
    }
}
c0der
  • 18,467
  • 6
  • 33
  • 65
dsncode
  • 2,407
  • 2
  • 22
  • 36
  • then you will need to iterate through all your elements and sort it every time. it might be better if you use employee's id as key. no? – dsncode Dec 22 '18 at 06:01
  • @MKumar i suggest you use id as key. in that fashion, you avoid linear time search by key and nlog time sorting – dsncode Jan 03 '19 at 15:06