在值上排序树形图

Joh*_*ohn -1 java

可能重复:
如何在Java中的值上对Map <Key,Value>进行排序?

我有一个treemap<Integer,Float>.如何在浮点数上对地图进行排序?

有什么快捷的方法吗?或者我必须为地图写比较器?

Lou*_*man 5

实际上,您无法(正确,可靠地)Map按值对实现进行排序.(你可能会看到声称的实现是hackish,不可靠,并且行为非常奇怪 - 拒绝重复值,在尝试查看不在地图中的键时抛出异常,如果支持映射发生更改,则会出现无法恢复的损坏...)

而是明确地对条目列表进行排序:

List<Map.Entry<Integer, Float>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Float>>() {
  public int compare(Map.Entry<Integer, Float> e1, Map.Entry<Integer, Float> e2){
    return e1.getValue().compareTo(e2.getValue());
  }
});
Run Code Online (Sandbox Code Playgroud)

如果你喜欢,你可以把它放到LinkedHashMap:

Map<Integer, Float> sortedMap = new LinkedHashMap<Integer, Float>();
for (Map.Entry<Integer, Float> entry : list) {
  sortedMap.put(entry.getKey(), entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)

  • 正如我在答案中所说,没有可靠的实施方案可以这样做. (2认同)