Map(3)--treeMap的排序

本文介绍了在Java中如何使用TreeMap存储具有自定义排序规则的学生信息及其对应的城市名。通过两种方式实现排序:一种是在Student类中重写compareTo方法;另一种是传入自定义的比较器Comparator。示例代码展示了不同情况下TreeMap的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当key是Student类对象,value是String型时,
(一) 在Student类中重写compareTo方法

    @Override
public int compareTo(student o) {
    int num=this.age-o.age;
    return num==0?this.name.compareTo(o.name):num;
}

回到主函数,

    public static void demo1() {
    TreeMap<student,String> tm=new TreeMap<student,String>();
    tm.put(new student("张三",23), "北京");
    tm.put(new student("赵六",13), "上海");
    tm.put(new student("李四",24), "广州");
    tm.put(new student("王五",25), "深圳");

    System.out.println(tm);
}

(二)传入比较器Comparator《E》

    public static void demo2() {
    TreeMap<student,String> tm=new TreeMap<student,String>(
            new Comparator<student>(){
                @Override
                public int compare(student s1, student s2) {
                    int num=s1.getName().compareTo(s2.getName());
                    return num==0?s1.getAge()-s2.getAge():num;
                }

            });
    tm.put(new student("张三",23), "北京");
    tm.put(new student("赵六",13), "上海");
    tm.put(new student("李四",24), "广州");
    tm.put(new student("王五",25), "深圳");

    System.out.println(tm);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值