Java 对象数组按某个属性排序

2021-08-20  本文已影响0人  赵哥窟

新建一个Student对象

public class Student {

    private String name;

    private double score;

    public Student(String name,double score) {
        super();
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }
}
public class Main {

    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();
        for(int i=0;i<10;i++){
            Student student = new Student("学生"+(i+1),10.0+i);
            studentList.add(student);
        }

       //按分数排序
        Collections.sort(studentList, (o1, o2) -> {
            if(o1.getScore() < o2.getScore())return 1;
            else return -1;
        });
        System.out.println("================降序排序结果================");
        printList(studentList);

       //按分数排序
        Collections.sort(studentList, (o1, o2) -> {
            if(o1.getScore() > o2.getScore())return 1;
            else return -1;
        });
        System.out.println("================升序排序结果================");
        printList(studentList);

    }

    private static void printList(List<Student> students){
        for (Student student : students) {
            System.out.println(student.toString());
        }
    }
上一篇下一篇

猜你喜欢

热点阅读