31 lines
966 B
Java
31 lines
966 B
Java
package me.konsolas.aac.util.general;
|
|
|
|
import java.util.Collections;
|
|
import java.util.Comparator;
|
|
import java.util.LinkedHashMap;
|
|
import java.util.LinkedList;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Map.Entry;
|
|
|
|
public class MapUtil {
|
|
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDescending(Map<K, V> map) {
|
|
List<Entry<K, V>> entries = new LinkedList<>(map.entrySet());
|
|
Collections.sort(entries, new DescendingValueComparator<>());
|
|
Map<K, V> sorted = new LinkedHashMap<>();
|
|
|
|
for (Entry<K, V> entry : entries) {
|
|
sorted.put(entry.getKey(), entry.getValue());
|
|
}
|
|
|
|
return sorted;
|
|
}
|
|
|
|
private static final class DescendingValueComparator<K, V extends Comparable<? super V>> implements Comparator<Entry<K, V>> {
|
|
@Override
|
|
public int compare(Entry<K, V> first, Entry<K, V> second) {
|
|
return second.getValue().compareTo(first.getValue());
|
|
}
|
|
}
|
|
}
|