map根据属性排序、取出map前n个
/**
* map根据value排序
* flag = 1 正序
* flag = 0 倒序
*
* @param map
* @param flag
* @return
*/
public static <K, V extends Comparable<? super V>> LinkedHashMap<K, V> sortByValue(Map<K, V> map, int flag) {
LinkedHashMap<K, V> sortMap = new LinkedHashMap<>();
if (flag == 1) {
map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).forEach(entry -> sortMap.put(entry.getKey(), entry.getValue()));
} else {
map.entrySet().stream().sorted((o1, o2) -> o2.getValue().compareTo(o1.getValue())).forEach(entry -> sortMap.put(entry.getKey(), entry.getValue()));
}
return sortMap;
}
/**
* 取出map前n个
*
* @param map
* @param length
* @return
*/
@Override
public LinkedHashMap<String, Double> subMap(LinkedHashMap<String, Double> map, int length) {
List<Map.Entry<String, Double>> lists = new ArrayList<>(map.entrySet());
LinkedHashMap<String, Double> sortedMap = new LinkedHashMap<>();
if (lists.size() >= length) {
for (Map.Entry<String, Double> set : lists.subList(0, length)) {
sortedMap.put(set.getKey(), set.getValue());
}
} else {
for (Map.Entry<String, Double> set : lists) {
sortedMap.put(set.getKey(), set.getValue());
}
}
return sortedMap;
}
本博客文章均已测试验证,欢迎评论、交流、点赞。
部分文章来源于网络,如有侵权请联系删除。
转载请注明原文链接:https://www.cnblogs.com/sueyyyy/p/11793746.html

浙公网安备 33010602011771号