Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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