HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("a", 4);
map.put("c", 6);
map.put("b", 2);
Run Code Online (Sandbox Code Playgroud)
期望的输出(HashMap):
c : 6
a : 4
b : 2
Run Code Online (Sandbox Code Playgroud)
我无法找到任何有关按价值降序的信息.
怎么能实现这一目标?(额外课程不是首选)
Evg*_*eev 23
试试这个:
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 4);
map.put("c", 6);
map.put("b", 2);
Object[] a = map.entrySet().toArray();
Arrays.sort(a, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Map.Entry<String, Integer>) o2).getValue()
.compareTo(((Map.Entry<String, Integer>) o1).getValue());
}
});
for (Object e : a) {
System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : "
+ ((Map.Entry<String, Integer>) e).getValue());
}
Run Code Online (Sandbox Code Playgroud)
输出:
c : 6
a : 4
b : 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28195 次 |
| 最近记录: |