Java: sort map by values and get top N keys?

22 October 2014

Here are two utility functions to do exactly that using Guava, inspired by this stackoverflow answer.

If the values are Comparable:

public static <K, V extends Comparable<?>> List<K> getTopKeys(Map<K, V> map, int n) {
  Function<K, V> getVal = Functions.forMap(map);
  Ordering<K> ordering = Ordering.natural().onResultOf(getVal);
  return ordering.greatestOf(map.keySet(), n);
}

If the values are not comparable, you'll need to pass in a comparator:

public static <K, V> List<K> getTopKeys(Map<K, V> map, Comparator<V> comp, int n) {
  Function<K, V> getVal = Functions.forMap(map);
  Ordering<K> ordering = Ordering.from(comp).onResultOf(getVal);
  return ordering.greatestOf(map.keySet(), n);
}