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 和流按值对地图进行排序


基础教程推荐
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01