【发布时间】:2020-05-24 21:40:32
【问题描述】:
我想对以LinkedList<Integer> 为键、float[] 为值的 LinkedHashMap 进行排序。
例如,假设我有这样的 LinkedHashMap:
LinkedHashMap<LinkedList<Integer>, float[]> hm = new LinkedHashMap<>();
LinkedList<Integer> linkedlist;
linkedlist = new LinkedList<>();
linkedlist.add(10);
linkedlist.add(7);
hm.put(linkedlist, new float[]{0.14f, 1.2f, 85.01f});
linkedlist = new LinkedList<>();
linkedlist.add(0);
linkedlist.add(41);
hm.put(linkedlist, new float[]{10.3f, 50.05f, 9.9f});
linkedlist = new LinkedList<>();
linkedlist.add(210);
linkedlist.add(3);
hm.put(linkedlist, new float[]{17.0f, 4.0f, 2.1f});
现在我想要的是输出:
{0, 41}, {10.3f, 50.05f, 9.9f}
{10, 7}, {0.14f, 1.2f, 85.01f}
{210, 3}, {17.0f, 4.0f, 2.1f}
但是当我使用建议的解决方案时(你们中的一些人在 cmets 部分建议说它是另一个已经有正确答案的帖子的重复 - 下面的帖子,链接到它here)它创建了新的 LinkedHashMap (因为我不知道如何通过这段代码对原始的 LinkedHashMap 进行排序,不幸的是)像这样:
LinkedHashMap<LinkedList<Integer>, float[]> sortedMap = new LinkedHashMap<>();
hm.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
hm = sortedMap;
我的 NetBeans 8.0.2 向我显示关于 .sorted(Map.Entry.comparingByKey()) 行的错误:
incompatible types: inference variable K has incompatible bounds
equality constraints: LinkedList<Integer>
upper bounds: Comparable <? super K>
where K,V are type-variables:
K extends Comparable<? super K> declared in method <K,V>comparingByKey()
V extends Object declared in method <K,V>comparingByKey()
我认为可能由于某种原因 LinkedList 中的值是错误的,所以我这样测试它,它表明这些都是正确的(我只测试了前 50 个条目,因为列表中有数百个条目):
for (int i = 0; i < hm.size(); i++) {
if (i < 50) {
for (Map.Entry<LinkedList<Integer>, float[]> entry : hm.entrySet()) {
LinkedList<Integer> k = entry.getKey();
System.out.println(k);
}
}
}
【问题讨论】:
-
数组不适合作为 Maps 的键,所以我先将键更改为
List<Integer> -
来自the documentation of
HashMap: "...此类不保证地图的顺序..." -
@Turing85 好的,我通过将 HashMap 更改为 LinkedHashMap 稍微更新了我的问题,这样它就可以满足要求 ;-)
-
我觉得这个问题的答案中已经说明了这一点。但是,正如答案所说,您不能这样做。 t 和 a 都将具有不同的 hashCode() 值,因为 java.lang.Array.hashCode() 方法继承自 Object,它使用引用来计算哈希码(默认实现)。因此,数组的哈希码是依赖于引用的,这意味着您将获得 t 和 a 的不同哈希码值。此外,equals 不适用于两个数组,因为这也是基于引用。当然,您可能有一个数组,但有一些概念
-
您的键是长度为 2 的列表。您想如何将它们相互比较?
LinkedList没有实现Comparable。
标签: java arrays sorting hashmap