Skip to content

Instantly share code, notes, and snippets.

@huantt
Last active June 26, 2016 13:43
Show Gist options
  • Save huantt/5663fdd132d2e1faae6c167c7e0ea163 to your computer and use it in GitHub Desktop.
Save huantt/5663fdd132d2e1faae6c167c7e0ea163 to your computer and use it in GitHub Desktop.
Dùng comparator sắp xếp Object theo thuộc tính
//Class Main
public class Test {
public static void main(String[] args) {
Nguoi n1 = new Nguoi("A");
Nguoi n2 = new Nguoi("C");
Nguoi n3 = new Nguoi("B");
Nguoi[] n = new Nguoi[3];
n[0] = n1;
n[1] = n2;
n[2] = n3;
Arrays.sort(n,new SortByName());
for (Nguoi nguoi : n) {
System.out.println(nguoi.getTen());
}
}
//Class Nguoi:
Class Nguoi{
String ten;
public String getTen(){
return this.ten;
}
}
public class SortByName implements Comparator<Nguoi> {
// Ham compare se dinh nghia cach so sanh,
//sau do dung no de truyen vao ham Collections.sort(list,CachSX);
// Neu bang nhau thi return 0
// Neu o1 hon o2 thi return 1 so lon hon 0 (Thuong dung 1)
// Neu o1 nho hon o2 thi return 1 so nho hon 0( Thuong la -1)
@Override
public int compare(Nguoi o1, Nguoi o2) {
int resurl;
resurl = o1.getTen().compareTo(o2.getTen());
return resurl;
}
}
// Cach 2 la khong can tao class SortByName ma khai bao 1 doi tuong Comparator luon roi override lai:
public void sortPeople() {
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Nguoi n1, Nguoi n2) {
return n1.getName().compareTo(n2.getName());
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment