• 集合排序


    自定义排序:Comparator &  Comparable

    Comparable 结合 TreeSet 使用


    Student.java

    @Data
    @AllArgsConstructor
    public class Student implements Comparable<Student>{
    
        private String name;
        private int age;
    
        @Override
        public int compareTo(Student o) {
            return this.age > o.age ? 1 : -1;
        }
    }

    测试:

    @Test
        public void testComparable(){
            Student s1 = new Student("abb",12);
            Student s2 = new Student("aab",15);
            Student s3 = new Student("cbs",10);
            TreeSet<Student> treeSet = new TreeSet<>();
            Collections.addAll(treeSet,s1,s2,s3);
            System.out.println(treeSet);
        }

    输出结果:

    [Student(name=cbs, age=10), Student(name=abb, age=12), Student(name=aab, age=15)]

    自定义排序:Comparator 结合 Collections.sort( ) 使用


    MyComparator.java:

    @Data
    @AllArgsConstructor
    public class MyComparator implements Comparator<Object> {
    
        @Override
        public int compare(Object o1, Object o2) {
            Teacher t1 = (Teacher) o1;
            Teacher t2 = (Teacher) o2;
            if(t1.getAge()>t2.getAge()){
                return -1;
            }else if(t1.getAge()<t2.getAge()){
                return 1;
            }else{
                return 0;
            }
        }
    }

    Teacher.java:

    @Data
    @AllArgsConstructor
    public class Teacher {
        private String name;
        private int age;
    
    }

    测试:

    @Test
        public void testComparator(){
            Teacher t1 = new Teacher("abb",12);
            Teacher t2 = new Teacher("aab",15);
            Teacher t3 = new Teacher("cbs",10);
            List<Teacher> list = new ArrayList<>();
            Collections.addAll(list,t1,t2,t3);
            System.out.println("排序前:
    "+list);
            Collections.sort(list,new MyComparator());
            System.out.println("排序后:
    "+list);
        }

    结果:

    排序前:
    [Teacher(name=abb, age=12), Teacher(name=aab, age=15), Teacher(name=cbs, age=10)]
    排序后:
    [Teacher(name=aab, age=15), Teacher(name=abb, age=12), Teacher(name=cbs, age=10)]

    爱来爱去没了反应 灯火惊动不了神经 有时爱情~徒有虚名

  • 相关阅读:
    ML(5)——神经网络1(神经元模型与激活函数)
    ML(4)——逻辑回归
    ML(附录3)——过拟合与欠拟合
    多变量微积分笔记24——空间线积分
    iOS开发--横向流水布局实现
    李洪强和你一起学习前端之面试题
    前端面试题 -- JS篇
    很强大的HTML+CSS+JS面试题(附带答案)
    李洪强iOS之集成极光推送三iOS集成指南
    李洪强iOS之集成极光推送二iOS 证书 设置指南
  • 原文地址:https://www.cnblogs.com/kongieg/p/12180205.html
Copyright © 2020-2023  润新知