Skip to content

Instantly share code, notes, and snippets.

@hugmanrique
Last active June 11, 2016 06:38
Show Gist options
  • Save hugmanrique/505a9195a3a2567e4c3a5db0cbb6dac7 to your computer and use it in GitHub Desktop.
Save hugmanrique/505a9195a3a2567e4c3a5db0cbb6dac7 to your computer and use it in GitHub Desktop.
Method used to order a Map<K, V extends Comparable>. Asked by @MxJesusDiaz at Twitter
/**
* Orders a {@code Map<K, V>}
* @param map The {@link Map} that will be ordered (The value types must extend {@link Comparable})
* @param <K> The {@code K} value. Any type is supported
* @param <V> The {@code V} value. Must extend {@link Comparable}
* @return The sorted {@link Map} ordered by values with {@link Comparable#compareTo(Object)}
* @author Hugmanrique <contact@hugmanrique.me>
* @see {@link Collections#sort(List)} to order the values
*/
public static <K, V extends Sort.Comparable> Map<K, V> orderMapByValues(Map<K, V> map){
//Firstly, create a LinkedList to know with values go with each key
List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
//Sort the values in the List with a comparator
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
//Let Java compare this automatically. Could do it manually returning -1, 0 or 1
return (o1.getValue()).compareTo(o2.getValue());
}
});
//The result Map (LinkedHashMap to conserve the order rather that by Object.hashCode())
Map<K, V> result = new LinkedHashMap<>();
//Fill the Map with the ordered values
for (Map.Entry<K, V> entry : list){
result.put(entry.getKey(), entry.getValue());
}
//Return the new map
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment