Showing posts with label Collection. Show all posts
Showing posts with label Collection. Show all posts

How to Sort HashMap by Values . Write Own Compare Method in Java Example

We can sort the Hashmap by putting all values in a TreeMap . By default TreeMap is sorted by Keys. To sort it by values , we have to write own compare method of comparator interface. The compare method compares its two arguments . By default two arguments are objects which is having key of Map. If both arguments are equal then it returns 0 . If first argument is less than the second argument , returns a negative integer, If first argument is greater than the second argument , returns a Positive integer. Now we have to sort by values. So we have to get the values using key i.e map.get(key) . Now we have to write our own logic to compare the values . The return value will be 0 or 1 or -1 . If more than one elements are equal it adds only the first value. If both arguments are equal means it returns 0 that means Hashmap is having duplicate values. As HashMap does not allow duplicate values ,to allow duplicate values , we have to return other than 0 value. In our example , when both values are equal , we compare both keys rather than values , thus returns other than 0. The following program is compatible for sorting of strings and also positive numbers. Negative numbers are sorted properly because we are using String.compareTo to compare two values. So it is always better to pass same type of values and change the compareTo logic accordingly. For example if all the values are integer means , the logic will be Integer e1 = (Integer)thisMapValues.get(o1); Integer e2 = (Integer) thisMapValues.get(o2); if (e1==e2) return return String.valueOf(o1).compareTo(String.valueOf(o2)) ; else if (e1<e2) return -1 ; else return 1;

import java.util.*;
public class HashMapSortValue{
private static class OwnCompare implements Comparator
{
private Map thisMapValues = null;
public OwnCompare (Map mapValues)
{
super();
thisMapValues = mapValues;
}

public int compare(Object o1, Object o2)
{
String e1 = String.valueOf(thisMapValues.get(o1));
String e2 = String.valueOf( thisMapValues.get(o2));
if (e1.compareTo(e2)==0) return String.valueOf(o1).compareTo(String.valueOf(o2)); else return e1.compareTo(e2);

}
}

public static void main(String[] args) {
Map hm = new HashMap();
hm.put ("Employee1", 60000);
hm.put ("Employee2", 50000);
hm.put ("Employee2", "absent");
hm.put ("Employee3", 25000);
hm.put ("Employee4","retired");
hm.put ("Employee5","absent");
hm.put ("Employee6",20000);
hm.put ("Employee7",20000);
hm.put ("Employee8",50000);
hm.put ("Employee9",60000);
System.out.println("List Before Sorting : " + hm);
SortedMap sortedByValue = new TreeMap(new HashMapSortValue.OwnCompare(hm));
sortedByValue.putAll(hm);
System.out.println("List After Sorting by Value " +sortedByValue);
}
}


Output :

Read more...

 
Copyright 2011 Java Online