java对LIst的排序

准备排序的实体类

 
 
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());
});

猜你喜欢

转载自www.cnblogs.com/zbbiex/p/10563985.html
今日推荐