Java tutorial
//package com.java2s; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; public class Main { @SuppressWarnings("unchecked") static public LinkedHashMap<Object, Comparable> sortHashMapByValues(HashMap<Object, Comparable> passedMap) { ArrayList mapKeys = new ArrayList(passedMap.keySet()); ArrayList mapValues = new ArrayList(passedMap.values()); Collections.sort(mapValues); Collections.sort(mapKeys); LinkedHashMap<Object, Comparable> sortedMap = new LinkedHashMap<Object, Comparable>(); Iterator<Comparable> valueIt = mapValues.iterator(); while (valueIt.hasNext()) { Comparable val = valueIt.next(); Iterator keyIt = mapKeys.iterator(); while (keyIt.hasNext()) { Object key = keyIt.next(); Comparable comp = passedMap.get(key); if (comp.equals(val)) { passedMap.remove(key); mapKeys.remove(key); sortedMap.put(key, val); break; } } } return sortedMap; } }