对LinkedHashMap进行排序

Ram*_*min 40 java linkedhashmap

如果LinkedHashMap包含String和Integer,我如何根据其值对LinkedHashMap进行排序.所以我需要根据整数值对它进行排序.非常感谢

Lou*_*man 71

List<Map.Entry<String, Integer>> entries =
  new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
  public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b){
    return a.getValue().compareTo(b.getValue());
  }
});
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> entry : entries) {
  sortedMap.put(entry.getKey(), entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)

  • 该死的,我写的是完全相同的代码!:)除了最后一部分,我认为OP实际上不需要让它们回到地图中. (4认同)
  • 您不需要更改比较器。您可以使用“Collections.reverseOrder(comparator)”,这使得含义更加明显。 (2认同)

spr*_*ter 35

现在使用Java 8流程非常简单:您不需要使用中间映射进行排序:

map.entrySet().stream()
    .sorted(Map.Entry.comparingByValue())
    .forEach(entry -> ... );
Run Code Online (Sandbox Code Playgroud)

  • 为什么这个答案会被接受并得到如此高的评价?它没有回答如何对地图本身进行排序。它只是告诉如何按特定顺序处理映射的内容。 (2认同)