首页 > 解决方案 > 如何将其解析为哈希图

问题描述

我有一个问题:我想返回一个排序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;
        }

标签: java

解决方案


仅使用排序列表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是合并函数,以防收集器发现重复键(在这种情况下不应该发生)。


推荐阅读