import java.util.*;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
Map<Integer, Double> Probs = new TreeMap<>();
Probs.put(1, 0.5);
Probs.put(2, 1.5);
Probs.put(3, 0.2);
Probs.put(4, 10.2);
Probs = sortByValueDescending(Probs);
System.out.println("基于value值的降序,排序输出结果为:");
for (Map.Entry<Integer, Double> entry : Probs.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
System.out.println();
System.out.println("基于value值的升序,排序输出结果为:");
Probs = sortByValueAscending(Probs);
for (Map.Entry<Integer, Double> entry : Probs.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
}
//降序排序
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDescending(Map<K, V> map)
{
return map.entrySet().stream().sorted(((o1, o2) -> o2.getValue().compareTo(o1.getValue())))
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(x,y)->x,LinkedHashMap::new));
}
//升序排序
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueAscending(Map<K, V> map)
{
return map.entrySet().stream().sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(x,y)->x,LinkedHashMap::new));
}
}
代码执行结果
--------------------------------------------分割线---------------------------------------------------------
下面是一些java相关的书籍,大家有兴趣的可以去下载看一下
以下书籍的提取码皆为:123456
《Java+8函数式编程》这本书强烈推荐(函数式编程和普通编程的对比,大概就是三维对二维。等你学会了可以对别人降维是打击)
https://306t.com/file/28095605-451122547
《深入理解Java虚拟机JVM高级特性与最佳实践(周志明)》(想深入了解虚拟机的同学可以收藏了)
https://306t.com/file/28095605-451122608
本文地址:https://blog.csdn.net/weixin_42440768/article/details/107403062
如对本文有疑问, 点击进行留言回复!!
springcloud中feign调用处理mybatis-plus Ipage反序列化问题。
Flume 史上最全面的大数据学习第十篇(一) 别再说不知道flume是什么了
网友评论