码迷,mamicode.com
首页 > 编程语言 > 详细

集合排序

时间:2020-01-11 16:41:55      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:sof   ring   pre   new   eset   this   data   sort   mil   

自定义排序: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("排序前:\n"+list);
        Collections.sort(list,new MyComparator());
        System.out.println("排序后:\n"+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)]

 

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

集合排序

标签:sof   ring   pre   new   eset   this   data   sort   mil   

原文地址:https://www.cnblogs.com/kongieg/p/12180205.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!