-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Class Nguoi: | |
Class Nguoi{ | |
String ten; | |
public String getTen(){ | |
return this.ten; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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