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)
spr*_*ter 35
现在使用Java 8流程非常简单:您不需要使用中间映射进行排序:
map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEach(entry -> ... );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59569 次 |
| 最近记录: |