1. 程式人生 > >java對LIst的排序

java對LIst的排序

println this pan ons set ring oid getname arraylist

準備排序的實體類


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的排序