在给定LinkedHashMap包含String和Integer的情况下,如何根据值对LinkedHashMap进行排序。所以我需要根据整数值对它进行排序。非常感谢
发布于 2015-01-09 20:15:09
现在使用Java 8 streams更容易了:您不需要中间映射即可进行排序:
map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEach(entry -> ... );发布于 2012-08-30 02:40:20
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());
}发布于 2012-08-30 02:37:12
LinkedHashMap只维护插入顺序。如果您希望根据值进行排序,则可能需要编写自己的comparator。
https://stackoverflow.com/questions/12184378
复制相似问题