Ví du 1: Sắp xếp theo điểm
public void sortGpa() {
// Cach 1: Khai báo bình thường
Collections.sort(studentlist, new Comparator<StudentModel>() {
@Override
public int compare(StudentModel o1, StudentModel o2) {
if (o1.getGpa() < o2.getGpa()) return -1;
return 1;
}
});
// Cach 2: khai báo cấu trúc rút gọn
Collections.sort(studentlist, (o1, o2) -> {
if (o1.getGpa() < o2.getGpa())
return -1;
return 1;
});
studentlist.forEach((list) -> {
list.display();
});
}
Ví dụ 2: Sắp xếp theo Name.
public void sortName() {
//Khai báo kiểu bình thường
Collections.sort(studentlist, new Comparator<StudentModel>() {
@Override
public int compare(StudentModel o1, StudentModel o2) {
return o1.getName().compareTo(o2.getName());
}
});
//Khai báo kiểu rút gọn
Collections.sort(studentlist, (o1, o2) -> o1.getName().compareTo(o2.getName()));
studentlist.forEach((list) -> {
list.display();
});
}
