1. 程式人生 > >Android List(集合)中的物件以某一個欄位排序

Android List(集合)中的物件以某一個欄位排序

在Android開發中,有時我們需要對一個物件的集合按照某一個欄位進行排序,

  • Bean
public class Student {
    private int studentId;
    private String studentName;
    private int age;
    public Student(int studentId , String studentName, int age){
        this.studentId=studentId;
        this.studentName=studentName;
        this
.age=age; } public int getStudentId() { return studentId; } public void setStudentId(int studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this
.studentName = studentName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
  • 實現排序

    實現排序比較類 Comparator ,裡面實現排序規則。

public class test {

    /**
     * @param args
     */
    public static void main(String[] args) {
         Student stu1 = new
Student (1,"zhangsan",28); Student stu2 = new Student (2,"zhagnsan",19); Student stu3 = new Student (3,"wangwu",19); Student stu4 = new Student (4,"wangwu",19); Student stu5 = new Student (5,"zhaoliu",18); ArrayList<Student> list = new ArrayList<Student>(); list.add(stu1); list.add(stu2); list.add(stu3); list.add(stu4); list.add(stu5); //排序規則,這裡是以年齡先排序,如果年齡相同 Comparator<Student> comparator = new Comparator<Student>() { public int compare(Student s1, Student s2) { // 先排年齡 if (s1.getAge() != s2.getAge()) { return s1.getAge() - s2.getAge(); } else if (!s1.getStudentName().equals(s2.getStudentName())) { // 年齡相同則按姓名排序 return s1.getStudentName().compareTo(s2.getStudentName()); } else { // 姓名也相同則按學號排序 return s1.getStudentId() - s2.getStudentId(); } } }; //這裡就會自動根據規則進行排序 Collections.sort(list,comparator); for(int i=0;i<list.size();i++){ Student stu=list.get(i); System.out.println("年齡:"+stu.getAge()+" 姓名:"+stu.getStudentName()+" 學號:"+stu.getStudentId()); } } }

排序結果

結果:
年齡:18   姓名:zhaoliu   學號:5
年齡:19   姓名:wangwu   學號:3
年齡:19   姓名:wangwu   學號:4
年齡:19   姓名:zhagnsan   學號:2
年齡:28   姓名:zhangsan   學號:1

也可以想下面這樣寫:

    Collections.sort(list, new Comparator<GoodsBean>() {
            @Override
            public int compare(GoodsBean bean1, GoodsBean bean2) {

                if (Integer.valueOf(bean1.getScore()).compareTo(Integer.valueOf(bean2.getScore())) == 0) {
                    return Integer.valueOf(bean1.getRecommend_num()).compareTo(Integer.valueOf(bean2.getRecommend_num()));
                } else {
                    return Integer.valueOf(bean1.getScore()).compareTo(Integer.valueOf(bean2.getScore()));
                }
            }
        });

這樣就可以對一個集合中的資料各種排序了。