Java中集合的自定义对象排乱,升,降序

Java中集合的数字排乱,升,降序
(代码如下,需要练习请自取)
1.建Student类


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Comparable<Student> {
    private int id;
    private String name;
    private int score;
    private String address;

    /**
     * 默认排序
     *
     * @param o the object to be compared.
     * @return
     */
    @Override
    public int compareTo(Student o) {
        //this a  o b  (a,b) -> a.id - b.id
        return id - o.id;
    }
}

2.建排序类(类名自定义)


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Paixu {
    public static void main(String[] args) {
//自定义对象 排序
        List<Student> s = new ArrayList<>(List.of(
                new Student(10, "李四", 30, "郑州"),
                new Student(11, "张三", 90, "天津"),
                new Student(12, "李丽", 60, "郑州"),
                new Student(23, "张三丰", 80, "北京"),
                new Student(36, "王五", 20, "郑州"),
                new Student(100, "赵六", 10, "上海"),
                new Student(9, "李强", 39, "上海"),
                new Student(1, "李三", 99, "上海"),
                new Student(11000, "李磊", 89, "上海")
        ));

        System.out.println(s);

        Collections.shuffle(s);
        System.out.println(s);

        //Collections.sort(s); 这一行有错误,Student对象没有实现排序接口的相关的方法

        //Collections.sort(s,(a,b)->b.getId()-a.getId());
        //System.out.println(s);

        //Collections.sort(s,(a,b)->a.getName().compareTo(b.getName()));
        //System.out.println(s);

        //Collections.sort(s,(a,b)->b.getName().length() - a.getName().length());
        //System.out.println(s);


        //如果类实现了Comparable<cn.webrx.coll.Student>接口并实现了方法compareTo()
        //根据id的升序
        Collections.sort(s);
        System.out.println(s);


        Collections.sort(s,(o1,o2)->o2.getId()-o1.getId());
        System.out.println(s);

结果如下
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值