Tuesday, June 1, 2010

Sorting HashMap by Value in java

package sun.sort;

import java.util.*;

// for JDK 1.5 and above
/**
* sorting hashMap based on the value and if Hash map contains null or empty to
* be added in last elements of map
* @author akamesh
*/
public class HashMapSort {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Map hm = new HashMap();
hm.put("a", "0.2");
hm.put("b", "1.2");
hm.put("c", "3");
hm.put("d", "5");
hm.put("e", "1");
hm.put("f", "2");
hm.put("g", "0");
hm.put("h", "");
// To make insertion order of values to be same
Map hm1 = new LinkedHashMap();
Map hMap = new LinkedHashMap();
List sortedList = sortByValue(hm);

for (Iterator i = sortedList.iterator(); i.hasNext();) {
String key = (String) i.next();
String value = (String) hm.get(key);
if (value != null && value.equals("")) {
hMap.put(key, value);
} else {
hm1.put(key, hm.get(key));
}
System.out.printf("key: %s, value: %s\n", key, hm.get(key));
}

Iterator myVeryOwnIterator = hm1.entrySet().iterator();
while (myVeryOwnIterator.hasNext()) {
System.out.println(myVeryOwnIterator.next());
}
System.out.println("****MAPs contains No values *******");

Iterator myVeryOwnIterator1 = hMap.entrySet().iterator();
while (myVeryOwnIterator1.hasNext()) {
System.out.println(myVeryOwnIterator1.next());
}
hm1.putAll(hMap);

System.out.println("**** Final values *******");

Iterator myVeryOwnIterator2 = hm1.entrySet().iterator();
while (myVeryOwnIterator2.hasNext()) {
System.out.println(myVeryOwnIterator2.next());
}

}

public static List sortByValue(final Map m) {
List keys = new ArrayList();
keys.addAll(m.keySet());
System.out.println("keys" + keys);
Collections.sort(keys, new Comparator() {
public int compare(Object o1, Object o2) {
Object v1 = m.get(o1);
Object v2 = m.get(o2);
if (v1 == null) {
return (v2 == null) ? 0 : 1;
} else if (v1 instanceof Comparable) {
return ((Comparable) v1).compareTo(v2);
} else {
return 0;
}
}
});
return keys;
}
}


OUTPUT:

keys[d, a, h, c, f, g, b, e]
key: h, value:
key: g, value: 0
key: a, value: 0.2
key: e, value: 1
key: b, value: 1.2
key: f, value: 2
key: c, value: 3
key: d, value: 5
g=0
a=0.2
e=1
b=1.2
f=2
c=3
d=5
****MAPs contains No values *******
h=
**** Final values *******
g=0
a=0.2
e=1
b=1.2
f=2
c=3
d=5
h=