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