Skip to content

Instantly share code, notes, and snippets.

@gbersac
Created November 14, 2014 16:44
Show Gist options
  • Save gbersac/8666ad9a7682d6d865ce to your computer and use it in GitHub Desktop.
Save gbersac/8666ad9a7682d6d865ce to your computer and use it in GitHub Desktop.
Sorting Map by value.
package misc;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class ArrayTools
{
private static class ValueComparator<K , V extends Comparable<V>> implements Comparator<K>
{
Map<K, V> map;
public ValueComparator(Map<K, V> map) {
this.map = map;
}
@Override
public int compare(K keyA, K keyB) {
Comparable<V> valueA = map.get(keyA);
V valueB = map.get(keyB);
return valueA.compareTo(valueB);
}
}
public static<K, V extends Comparable<V>> Map<K, V> sortByValue(Map<K, V> unsortedMap)
{
Map<K, V> sortedMap = new
TreeMap<K, V>(new ValueComparator<K, V>(unsortedMap));
sortedMap.putAll(unsortedMap);
return sortedMap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment