Skip to content

Instantly share code, notes, and snippets.

@scottcagno
Forked from gbersac/sort_map.java
Last active August 29, 2015 14:16
Show Gist options
  • Save scottcagno/4573d02509942548c99c to your computer and use it in GitHub Desktop.
Save scottcagno/4573d02509942548c99c to your computer and use it in GitHub Desktop.
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