java - 如何将其解析为哈希图
问题描述
我有一个问题:我想返回一个排序hashmap
但不幸的是它不再是一个 hasmap。我怎么能把它解析回一个hashmap
?
private HashMap<int[], Double> sortHashMap(HashMap<int[], Double> hashMap) {
HashMap<int[], Double> sortedHashMap = new HashMap<int[], Double>();
List<Entry<int[], Double>> list = new ArrayList<>(hashMap.entrySet());
list.sort(Entry.comparingByValue());
// sortedHashMap = list.sort(Entry.comparingByValue()); // not working :(
return sortedHashMap;
}
解决方案
仅使用排序列表sort
不会给您返回地图。您也不能使用 aHashMap
来构建排序地图。LinkedHashMap
收集列表条目时使用 a保留顺序:
private LinkedHashMap<int[], Double> sortHashMap(HashMap<int[], Double> hashMap) {
List<Entry<int[], Double>> list = new ArrayList<>(hashMap.entrySet());
list.sort(Entry.comparingByValue());
return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(key1, key2) -> key2, LinkedHashMap::new));
}
请注意,第三个参数(key1, key2) -> key2
是合并函数,以防收集器发现重复键(在这种情况下不应该发生)。
推荐阅读
- laravel - 如何在 Laravel 5.5 中创建按日期分组的两个模型的集合?
- macos - 排版 -U PATH 在 macOS 终端 zsh 中不起作用
- javascript - Odoo 覆盖 pos_discount 模块中的函数/无法在我的自定义模块中继承 pos_discount 模块
- javascript - 如何在 JavaScript 中将多个 .textcontents 设置为单击事件?
- java - checkstyle 配置失败:无法解析配置流
- c++ - 红外接收器多频
- java - 如何将 textView 文本转换为 char 变量?
- url-rewriting - URL 重写在更高的环境中不起作用(未捕获的 ReferenceError:$ 未定义)
- elasticsearch - 嵌套弹性搜索嵌套查询问题 ES7.2
- ffmpeg - 如何从头开始观看或下载潜望镜直播?