有没有一种方便的方法可以从HashMap的值生成一个排序数组?

huangapple go评论92阅读模式
英文:

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&lt;CustomClass, Double&gt; 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&lt;CustomClass&gt;() {
  public int compare(CustomClass a, CustomClass b) {
    return Double.compare(map.get(a), map.get(b));
  }
}

huangapple
  • 本文由 发表于 2020年8月30日 01:04:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63649664.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定