public class Test {
public static void main(String[] args) throws ClassNotFoundException {
// TODO Auto-generated method stub
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("d", 2);
map.put("c", 1);
map.put("b", 4);
map.put("a", 3);
map.put("e", 5);
List<Map.Entry<String, Integer>> list =
new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
for (int i = 0; i < list.size(); i++) {
String id = list.get(i).toString();
System.out.println(id);
}
System.out.println("-------------按value排序----------------------------");
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o1.getValue() - o2.getValue());
}
});
for (int i = 0; i < list.size(); i++) {
String id = list.get(i).toString();
System.out.println(id);
}
System.out.println("--------------按key排序-----------------------------");
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
for (int i = 0; i < list.size(); i++) {
String id = list.get(i).toString();
System.out.println(id);
}
}
}
result:
d=2
e=5
b=4
c=1
a=3
-------------按value排序----------------------------
c=1
d=2
a=3
b=4
e=5
--------------按key排序-----------------------------
a=3
b=4
c=1
d=2
e=5
java Map 按value值排序和按key值排序
最新推荐文章于 2022-09-19 19:38:23 发布