美文网首页
Java 对象数组按某个属性排序

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

作者: 赵哥窟 | 来源:发表于2021-08-20 15:46 被阅读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());
            }
        }
    

    相关文章

      网友评论

          本文标题:Java 对象数组按某个属性排序

          本文链接:https://www.haomeiwen.com/subject/izutiltx.html