Sort map by value using lambdas and streams(使用 lambda 和流按值对地图进行排序)
问题描述
I'm new to Java 8, not sure how to use streams and it's methods to sort. If I have map as below, how to sort this map by value to take only top 10 entries using Java 8.
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 10);
map.put("b", 30);
map.put("c", 50);
map.put("d", 40);
map.put("e", 100);
map.put("f", 60);
map.put("g", 110);
map.put("h", 50);
map.put("i", 90);
map.put("k", 70);
map.put("L", 80);
I know before Java 8, we can sort as this link: https://stackoverflow.com/a/109389/4315608
You can always start reading the documentation and some tutorials.
map.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.limit(10)
.forEach(System.out::println); // or any other terminal method
Reference
http://www.leveluplunch.com/java/examples/sort-order-map-by-values/
这篇关于使用 lambda 和流按值对地图进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 lambda 和流按值对地图进行排序
基础教程推荐
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- JPA惰性列表上的流 2022-01-01
