英文:
Is there a convenient way to generate a sorted array from the values of a HashMap?
问题
我有一个 HashMap<CustomClass, Double>
,我在循环内部填充它,我想生成一个按照HashMap中相应的double值排序的 CustomClass[]
数组。
我可以通过在循环外部初始化一个空的双精度数组,然后用与HashMap中值相同的双精度值填充它来实现这一点。循环结束后,我可以使用类似 Arrays.sort(my_doubles_array)
的方法对双精度数组进行排序,然后遍历数组,在比较HashMap的值并挑选出匹配的键。这种方法可以实现,但似乎存在一些不必要的工作。
有没有更好的方法可以实现这个需求呢?
英文:
I have a HashMap<CustomClass, Double>
that I'm populating inside a loop, and I'd like to produce a CustomClass[]
which is sorted by the corresponding doubles in my HashMap.
I can do this by initializing an empty array of doubles outside my loop and populating it with the same doubles that I used as values in my HashMap. After looping, I can use something like Arrays.sort(my_doubles_array)
to sort my doubles, then iterate through them, comparing HashMap values and picking out matching keys. This way works, but it seems like there's unnecessary work here.
Is there a way I can do this better?
答案1
得分: 5
使用流式处理:
CustomClass[] array =
map.entrySet().stream()
.sorted(comparingDouble(Entry::getValue))
.map(Entry::getKey)
.toArray(CustomClass[]::new);
不使用流式处理的另一种方法:
CustomClass[] array = map.keySet().toArray(new CustomClass[0]);
Arrays.sort(array, comparingDouble(map::get));
在 Java 8 之前,您可以通过使用匿名比较器(或类似方法)来实现:
new Comparator<CustomClass>() {
public int compare(CustomClass a, CustomClass b) {
return Double.compare(map.get(a), map.get(b));
}
}
英文:
Using streams:
CustomClass[] array =
map.entrySet().stream()
.sorted(comparingDouble(Entry::getValue))
.map(Entry::getKey)
.toArray(CustomClass[]::new);
An alternative without streams:
CustomClass[] array = map.keySet().toArray(new CustomClass[0]);
Arrays.sort(array, comparingDouble(map::get));
And you can do it in pre-Java 8 by replacing the comparator with an anonymous comparator (or similar):
new Comparator<CustomClass>() {
public int compare(CustomClass a, CustomClass b) {
return Double.compare(map.get(a), map.get(b));
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论