How to sort HashMap/TreeMap based on value ?
Solution Logic: First we will have a normal HashMap/Treemap object and put some objects to it. Then we will put the same object to another TreeMap object.
class ValueComparator implements Comparator{ Map map; public ValueComparator(Map map) { this.map=map; } public int compare(Object o1, Object o2) { int i1=(Integer)map.get(o1); int i2=(Integer)map.get(o2); return i1-i2; //return i1.compareTo(i2);//If i1 and i2 were of Class type instead of primitives } } public class Manager { public static void main(String[] args){ Map map=new HashMap(); map.put("B", 5); map.put("A", 4); map.put("C", 2); map.put("E", 3); map.put("D", 1); map.put("G", 7); map.put("F", 6); System.out.println("Before sorting:"+map); Map map2=new TreeMap(new ValueComparator(map)); map2.putAll(map);//only when you start putting the objects again, it will start re-arranging System.out.println("After sorting:"+map2); } }
Below is another example using an class type (Employee object):
class Employee implements Comparator{ int age; Map map; public Employee(int age) { this.age=age; } public int compare(Object o1, Object o2) { Employee e1=(Employee)o1; Employee e2=(Employee)o2; return e1.age - e2.age; } public String toString() { return String.valueOf(age); } } class ValueComparator implements Comparator{ Map map; public ValueComparator(Map map) { this.map=map; } public int compare(Object o1, Object o2) { Employee e1 = (Employee) map.get(o1); Employee e2 = (Employee) map.get(o2); return e1.age - e2.age; } } public class Manager{ public static void main(String[] args) { Employee e1=new Employee(41); Employee e2=new Employee(35); Employee e3=new Employee(10); Map map=new TreeMap(new Employee(5));// map.put(e1, e2); map.put(e3, e3); map.put(e2, e1); System.out.println(map); Map map2=new TreeMap(new ValueComparator(map)); map2.putAll(map); //only when you start putting the objects again, it will start re-arranging System.out.println(map2); } }