使用List集合中的sort(Comparator<? super E> var1)方法。
1,先把Map转化为Set集合:map.EntrySet(),使用ArrayList<Collection<? extends E> c)构造器,将Set集合传入其中。
2,使用List集合中的sort(Comparator<? super E> var1)方法进行排序
① args1 > args2 返回正整数
② args1 < args2 返回负整数
③ args1 = args2 返回 0
①、②、③ => 升序
倒序则将 ①和② 返回值 调换
/// 把学生名与考试分数录入到Map中,并按分数显示前三名成绩学员的名字。
@Test
public void test(){
LinkedHashMap<String, Integer> studentInfo = new LinkedHashMap<>();
studentInfo.put("佐助",88);
studentInfo.put("鸣人",90);
studentInfo.put("带土",80);
studentInfo.put("斑爷",100);
studentInfo.put("小樱",90);
studentInfo.put("鹿丸",80);
List<Map.Entry<String,Integer>> infos = new ArrayList<>(studentInfo.entrySet());
infos.sort(new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> t0,
Map.Entry<String, Integer> t1) {
return t1.getValue() - t0.getValue();
}
});
Iterator<Map.Entry<String, Integer>> iterator = infos.iterator();
int count = 0;
System.out.println("前三名的成绩为:");
while(iterator.hasNext() && count < 3){
count++;
System.out.println(iterator.next());
}
}