zoukankan      html  css  js  c++  java
  • 关于List集合中元素排序问题

    问题描述:

    有一个list集合,其中元素是Student对象,根据student的age排序。

    Student对象

    /**
     * description
     *
     * @author 70KG
     * @date 2018/9/29
     */
    @Data
    public class Student implements Comparable<Student> {
    
        private String name;
    
        private Integer age;
    
        private Integer num;
    
        public Student() {
        }
    
        public Student(String name, Integer age, Integer num) {
            this.name = name;
            this.age = age;
            this.num = num;
        }
    
        @Override
        public int compareTo(Student student) {
            return student.getAge().compareTo(this.getAge());
        }
    }

    此类需要实现Comparable接口,重写compareTo方法

    测试类:

    /**
     * description
     *
     * @author 70KG
     * @date 2018/9/29
     */
    public class TestController {
    
        public static void main(String[] args) {
    
            List<Student> list = new ArrayList<>();
    
            Student student1 = new Student("张三",21,1);
            Student student2 = new Student("李四",22,2);
            Student student3 = new Student("王五",23,3);
            Student student4 = new Student("赵六",24,4);
    
            list.add(student4);
            list.add(student1);
            list.add(student2);
            list.add(student3);
    
            System.out.println(list);
    
            Collections.sort(list);
    
            System.out.println(list);
        }
    
    }

    利用Collections.sort()方法进行重排序。

    输出结果:

    [Student(name=赵六, age=24, num=4), Student(name=张三, age=21, num=1), Student(name=李四, age=22, num=2), Student(name=王五, age=23, num=3)]
    [Student(name=赵六, age=24, num=4), Student(name=王五, age=23, num=3), Student(name=李四, age=22, num=2), Student(name=张三, age=21, num=1)]

    正序倒序,只需改变实体中的compareTo方法即可。

  • 相关阅读:
    19. vue的原理
    18.jwt加密
    17.vue移动端项目二
    16.vue-cli跨域,swiper,移动端项目
    15.vue动画& vuex
    14.vue路由&脚手架
    13.vue组件
    12.vue属性.监听.组件
    11.vue 数据交互
    从尾到头打印链表
  • 原文地址:https://www.cnblogs.com/zhangjianbing/p/9722210.html
Copyright © 2011-2022 走看看