?
- S?p x?p h? tên theo th? t? a, b, c.
- S?p x?p danh sách k?t qu? thi theo th? t? t? cao xu?ng th?p.
- S?p x?p tài li?u theo th? t? m?i tr??c, c? sau.
- ..v.v..
- Vi?c s?p x?p m?t các ??i t??ng trong 1 ArrayList có th? có nhi?u cách. Các b?n có th? áp d?ng các ph??ng pháp c? b?n, hoán ??i v? trí khi so sánh gi?ng nh? vi?c s?p x?p các ph?n t? trong m?ng ?ã dùng. Tuy nhiên, ? bài này mình s? gi?i thi?u 1 cách s?p x?p c?c ng?n g?n, Java ?ã h? tr? s?n, ?ó là ph??ng th?c s?p x?p Collection.sort.
- Mình s? nêu m?t vài ví d? c? th? ?? các b?n cùng tìm hi?u!
? các ví d? này, các thu?c tính ??i t??ng mình ?? public cho ng?n g?n, chúng ta t?p trung vào ?o?n s?p x?p!
Ví d? 1: S?p x?p m?t danh sách các ??i t??ng sinh viên có 2 thu?c tính h? tên và ?i?m thi.
Các b?n chú ý ?o?n này:
PHP:
//S?p x?p danh sách theo theo s? ?i?m gi?m d?n!
Collections.sort(danhSach, new Comparator<SinhVien>() {
@Override
public int compare(SinhVien sv1, SinhVien sv2) {
if (sv1.diem < sv2.diem) {
return 1;
} else {
if (sv1.diem == sv2.diem) {
return 0;
} else {
return -1;
}
}
}
});
- Ph??ng th?c public int compare(SinhVien sv1, SinhVien sv2) tr? v? ki?u giá tr? nguyên. ?o?n code trên là giúp s?p x?p theo th? t? gi?m d?n c?a s? ?i?m t?ng ??i t??ng sinh viên. N?u b?n mu?n s?p x?p t?ng d?n thì ??i ch? 1 và -1 cho nhau là ???c!
PHP:
Collections.sort(danhSach, new Comparator<SinhVien>() {
@Override
public int compare(SinhVien sv1, SinhVien sv2) {
if (sv1.diem < sv2.diem) {
return -1;
} else {
if (sv1.diem == sv2.diem) {
return 0;
} else {
return 1;
}
}
}
});
PHP:
package javaandroidvn;
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Scanner;
class SinhVien {
public String hoTen;
public int diem;
}
public class JavaAndroidVn {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Nh?p s? sinh viên: ");
int n = input.nextInt();
ArrayList<SinhVien> danhSach = new ArrayList();
for (int i = 0; i < n; i++) {
input.nextLine();
SinhVien x = new SinhVien();
System.out.println("Thông tin sinh viên th? " + i);
System.out.print("H? và Tên: ");
x.hoTen = input.nextLine();
System.out.print("?i?m: ");
x.diem = input.nextInt();
danhSach.add(x);
}
//S?p x?p danh sách theo s? ?i?m gi?m d?n!
Collections.sort(danhSach, new Comparator<SinhVien>() {
@Override
public int compare(SinhVien sv1, SinhVien sv2) {
if (sv1.diem < sv2.diem) {
return 1;
} else {
if (sv1.diem == sv2.diem) {
return 0;
} else {
return -1;
}
}
}
});
System.out.println("Danh sách s?p x?p theo th? t? ?i?m gi?m d?n là: ");
for (int i = 0; i < danhSach.size(); i++) {
System.out.println("Tên: " + danhSach.get(i).hoTen + " ?i?m: " + danhSach.get(i).diem);
}
}
}
PHP:
package javaandroidvn;
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Scanner;
class SinhVien {
public Available link for download