Comparator比较器的使用实操:根据Map集合中的value对Map进行排序

使用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());
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值