首页 > 编程语言 > 详细

java对LIst的排序

时间:2019-03-20 12:37:36      阅读:155      评论:0      收藏:0      [点我收藏+]

准备排序的实体类


public class Student {
private Integer index;
private String name;
private Integer age;

public Student() {
}

public Student(Integer index, String name, Integer age) {
this.index = index;
this.name = name;
this.age = age;
}

public Integer getIndex() {
return index;
}

public void setIndex(Integer index) {
this.index = index;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

}
 
List<Student> students = new ArrayList<>();
students.add(new Student(1,"z1",25));
students.add(new Student(12,"z2",26));
students.add(new Student(9,"z3",27));
students.add(new Student(4,"z4",28));
students.add(new Student(1,"z5",29));

1,java8之前对集合排序

//java8之前的排序
Collections.sort(students,new ComparatorChain<Student>(){
     public int compare(Student s1, Student s2) {
          return s1.getIndex().compareTo(s2.getIndex());
     }
});
students.forEach(s->{
     System.out.println(s.toString());
});

结果:

Student{index=1, name=‘z1‘, age=25}
Student{index=1, name=‘z5‘, age=29}
Student{index=4, name=‘z4‘, age=28}
Student{index=9, name=‘z3‘, age=27}
Student{index=12, name=‘z2‘, age=26

3,java8对集合优雅排序

(1)

studentList.sort((Student s1,Student s2)->s1.getIndex().compareTo(s2.getIndex()));
studentList.forEach(s -> {
   System.out.println(s.toString());
});

(2)

Collections.sort(studentList, Comparator.comparing(Student::getIndex));
studentList.forEach(s -> {
    System.out.println(s.toString());
});

 

java对LIst的排序

原文:https://www.cnblogs.com/zbbiex/p/10563985.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!