上代码:
import java.util.*;
public class Test7 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < 5; i++) {//插入随机数
map.put("a"+i,(int) (Math.random() * 10));
}
ArrayList<Map.Entry<String, Integer>> entryArrayList = new ArrayList<>(map.entrySet());
System.out.print("排序前:");
for (Map.Entry<String, Integer> entry : entryArrayList) {
System.out.print(entry.getKey()+"="+entry.getValue()+" ");
}
System.out.println();
Collections.sort(entryArrayList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue()-o1.getValue();//倒序
}
});
System.out.print("倒序排序后:");
for (Map.Entry<String, Integer> entry : entryArrayList) {
System.out.print(entry.getKey()+"="+entry.getValue()+" ");
}
System.out.println();
Collections.sort(entryArrayList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue()-o2.getValue();//正序
}
});
System.out.print("正序排序后:");
for (Map.Entry<String, Integer> entry : entryArrayList) {
System.out.print(entry.getKey()+"="+entry.getValue()+" ");
}
}
}
执行结果: