問題描述:
List中存放的是某個對象,現在要把這個集合根據對象的某個屬性進行排序,不過需要把要排序的屬性值變爲可運算的數值,才能實現此功能。
代碼示例如下:
import java.util.Collections;
import java.util.Comparator;
public class Test {
public static void main(String[] args) throws Exception {
//Student是一個對象,該對象中有個帶參數的構造方法
List<Student> ps = new ArrayList<Student>();
ps.add(new Student("h", "啊"));
ps.add(new Student("a", "中"));
ps.add(new Student("c", "寶"));
System.out.println("排序前");
for (Student o : ps) {
System.out.println(o.getValue().charAt(0)+" "+o.getName());
}
Collections.sort(ps, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//String類型進行排序
return return o1.getValue().compareTo(o2.getValue());
}
});
System.out.println("排序後");
for (Student o : ps) {
System.out.println(o.getValue().charAt(0)+" "+o.getName());
}
}
}
控制檯輸出內容爲:
排序前
啊 h
中 a
寶 c
排序後
中 a
啊 h
寶 c