java - 如何获得 HashMap 中的 3 个最高值?
问题描述
我有一个哈希图,如下所示:
HashMap<String, Integer> hm = new HashMap<String, Integer>;
hm.put("a", 1);
hm.put("b", 12);
hm.put("c", 53);
hm.put("d", 2);
hm.put("e", 17);
hm.put("f", 8);
hm.put("g", 8);
我将如何获得具有 3 个最高值的键?所以它会返回:
"c", "e", "b"
谢谢。
解决方案
我的解决方案,按值排序并获得前 3 名并返回键列表。
List<String> keys = hm.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue().reversed()).limit(3).map(Map.Entry::getKey).collect(Collectors.toList());
希望能帮助到你
推荐阅读
- ios - 如何使用 Swift 在 JKCalendar 事件列表中创建具有当前时间线显示的正确时间格式?
- java - Android 10 中的 Sql 语法错误,在其他版本中可以正常工作
- canvas - 在 webgl 中,透视相机被添加到画布或 3D 模型本身?
- google-cloud-platform - 为 GCP Bucket 中所有未来上传的对象设置默认元数据
- android - 无法同步 Gradle 项目并显示消息“读取超时”
- rxjs - 无法将 Observable 转换为 ConnectableObservable
- php - wp_query wordpress
- java - 我想创建一个包含我所有函数的 .class 文件。我无法编译它。我应该进口什么?
- c# - 我正在处理仅包含 3 个字段的新用户注册表单,用户名、密码和确认密码
- sql - 使用 ADO.net 将 100000 条记录从数据库绑定到 asp.netmvc 中的数据表时出现问题