zoukankan      html  css  js  c++  java
  • List集合中的对象进行排序

    类A:

      

        public  class A  implements Comparable<A>{
            private Integer id;
            private String name;
    
            public A(){
            }
            public A(Integer id , String name){
                this.id = id;
                this.name = name;
            }
    
            public Integer getId() {
                return id;
            }
    
            public void setId(Integer id) {
                this.id = id;
            }
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            @Override
            public String toString(){
                return "id:" + id + ";name:" + name;
            }
    
            @Override
            public int compareTo(A o) {
                //正序
                return o.getId().compareTo(this.getId());
                //倒序
                //return this.getId().compareTo(o.getId());
            }
        }
    

      

    类B:

        public  class B  {
            private Integer id;
            private String name;
    
            public B(){
            }
            public B(Integer id , String name){
                this.id = id;
                this.name = name;
            }
    
            public Integer getId() {
                return id;
            }
    
            public void setId(Integer id) {
                this.id = id;
            }
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            @Override
            public String toString(){
                return "id:" + id + ";name:" + name;
            }
        }
    

      

    (1)对象的类实现 Comparable 接口,直接调用,就可以实现排序

    Collections.sort(list);
    

    (2)sort(List<T> list, Comparator<? super T> c)

            Collections.sort(list2, new Comparator<B>() {
                @Override
                public int compare(B o1, B o2) {
                    //正序
    //                return o1.getId().compareTo(o2.getId());
                    //倒序
                    return o2.getId().compareTo(o1.getId());
                }
            });
    

      

      

  • 相关阅读:
    spring-boot-swagger2 使用手册
    mall整合Swagger-UI实现在线API文档
    MyBatis Generator 详解
    1046 划拳 (15分)
    1043 输出PATest (20分)
    1042 字符统计 (20分)
    1041 考试座位号 (15分)
    1040 有几个PAT (25分)
    1039 到底买不买 (20分)
    1038 统计同成绩学生 (20分)
  • 原文地址:https://www.cnblogs.com/knsbyoo/p/9140557.html
Copyright © 2011-2022 走看看