1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| public class MapUtils {
// Java 7
public static <K,V> Map<K, V> sortByValues(Map<K,V> map, final Comparator<V> comparator) {
final Set<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(new Comparator<Map.Entry<K,V>>() {
@Override
public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) {
return comparator.compare(e1.getValue(), e2.getValue());
}
});
sortedEntries.addAll(map.entrySet());
final Map<K, V> sortedMap = new LinkedHashMap<K, V>();
for(Map.Entry<K, V> entry : sortedEntries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
/*
// Java 8
public static <K,V> Map<K, V> sortByValues(Map<K,V> map, Comparator<V> comparator) {
return map.entrySet()
.stream()
.sorted((e1,e2)-> comparator.compare(e1.getValue(), e2.getValue()))
.collect(Collectors.toMap(e->e.getKey(),e->e.getValue(),(v1,v2)->v1,LinkedHashMap::new));
}
*/
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("A",1);
map.put("B",4);
map.put("C",2);
map.put("D",3);
map = MapUtils.sortByValues(map, Collections.reverseOrder()); // Java 7
//map = MapUtils.sortByValues(map, Comparator.reverseOrder()); // Java 8
System.out.println(map);
}
} |