如果LinkedHashMap包含String和Integer,我如何根据它的值对LinkedHashMap进行排序。 所以我需要根据整数值对它进行排序。 多谢
这在Java 8流中变得容易多了:你不需要中间地图来排序:
map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEach(entry -> ... );
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());
}
LinkedHashMap
只维护插入顺序。 如果要基于值进行排序,可能需要编写自己的比较器
。