Java: Sorting an hashmap according to its value

I had an HashMap composed with an object and an Integer value associated. By design, hashmaps are not ordered. Eventually, found around the web a nice method and modified the code to ensure it could be generic and ready to use with any kind of object.

Below you find the method ready to use. Attention to the copyright assignment (thanks WikiJava) where I'm referring the source from where the code derives.

 /**
     * Sort an hashmap according to its value.
     * @origin http://wikijava.org/wiki/Sort_a_HashMap
     * @date 2011-05-28
     * @modified http://nunobrito.eu
     * @date 2014-04-04
     */
private Map sortHashMap(HashMap input){
Map<Object,Integer> map = new LinkedHashMap<Object,Integer>();
List<Object> yourMapKeys = new ArrayList<Object>(input.keySet());
List<Integer> yourMapValues = new ArrayList<Integer>(input.values());
TreeSet<Integer> sortedSet = new TreeSet<Integer>(yourMapValues);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
for (int i=size-1; i>-1; i--) {
map.put
(yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])),
(Integer) sortedArray[i]);
}
return map;
}

Inside your code, you can use the snippet below. Attention that "FileLanguage" is the name of my object, you can replace this with a String or any other object you wish.

// sort the result
Map<Object,Integer> map = sortHashMap(statsLanguagesFound);
// show the ordered results
for(Object langObj :map.keySet()){
FileLanguage lang = (FileLanguage) langObj;
int count = map.get(lang);
System.out.println(lang.toString() + " -> " + count);
}


The end result is the following:

File: busybox-1.21.1.spdx
C -> 796
UNSORTED -> 674
SCRIPT_LINUX -> 19
HTML -> 9
PERL -> 3

File: flyingsaucer-R8.spdx
JAVA -> 4
UNSORTED -> 1

File: jfreechart-1.0.16.spdx
JAVA -> 1035
UNSORTED -> 57
HTML -> 48


Hope you find it useful.  :-)

No comments:

Post a Comment