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

Is there a convenient way to generate a sorted array from the values of a HashMap?

我有一个要在循环中填充的 HashMap<CustomClass, Double>,我想生成一个 CustomClass[],它按我的 HashMap 中相应的双精度排序。

我可以通过在我的循环外初始化一个空的双精度数组并用我在 HashMap 中用作值的相同双精度填充它来完成此操作。循环后,我可以使用 Arrays.sort(my_doubles_array) 之类的东西对我的双打进行排序,然后遍历它们,比较 HashMap 值并挑选出匹配的键。这种方式可行,但这里似乎没有必要的工作。

有什么办法可以做得更好吗?

使用流:

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));

您可以在 pre-Java 8 中通过用匿名比较器(或类似的)替换比较器来实现:

new Comparator<CustomClass>() {
  public int compare(CustomClass a, CustomClass b) {
    return Double.compare(map.get(a), map.get(b));
  }
}