首页 > 代码库 > java 对list中对象按属性排序

java 对list中对象按属性排序

实体对象类 --略

排序类----实现Comparator接口,重写compare方法

package com.tang.list;

import java.util.Comparator;

public class Mycompera implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        if (o1.getSid() > o2.getSid()) {
            return -1;
        }
        return 1;
    }

}

测试类--------------------------

package com.tang.list;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListSortTang {
    // 按照list 中对象的属性排序
    public static void main(String[] args) {
        Student st1 = new Student(1, "a", "男", 12);
        Student st2 = new Student(2, "b", "女", 11);
        Student st3 = new Student(3, "c", "男", 20);
        Student st4 = new Student(4, "d", "女", 15);
        Student st5 = new Student(5, "e", "男", 32);
        Student st6 = new Student(6, "f", "女", 21);
        Student st7 = new Student(7, "g", "男", 12);
        Student st8 = new Student(8, "h", "女", 10);
        Student st9 = new Student(9, "i", "男", 9);
        Student st10 = new Student(10, "j", "女", 19);
        List<Student> stus = new ArrayList<Student>();
        stus.add(st1);
        stus.add(st2);
        stus.add(st3);
        stus.add(st4);
        stus.add(st8);
        stus.add(st5);
        stus.add(st6);
        stus.add(st7);
        stus.add(st9);
        stus.add(st10);
        for (Student s : stus) {
            System.out.println(s.toString());
        }
        System.out.println("排序后.................");
        Collections.sort(stus, new Mycompera());// 排序
        for (Student s : stus) {
            System.out.println(s.toString());
        }
    }
}
输出-------------------

Student [sid=1, name=a, sex=男, age=12]
Student [sid=2, name=b, sex=女, age=11]
Student [sid=3, name=c, sex=男, age=20]
Student [sid=4, name=d, sex=女, age=15]
Student [sid=8, name=h, sex=女, age=10]
Student [sid=5, name=e, sex=男, age=32]
Student [sid=6, name=f, sex=女, age=21]
Student [sid=7, name=g, sex=男, age=12]
Student [sid=9, name=i, sex=男, age=9]
Student [sid=10, name=j, sex=女, age=19]
排序后.................
Student [sid=10, name=j, sex=女, age=19]
Student [sid=9, name=i, sex=男, age=9]
Student [sid=8, name=h, sex=女, age=10]
Student [sid=7, name=g, sex=男, age=12]
Student [sid=6, name=f, sex=女, age=21]
Student [sid=5, name=e, sex=男, age=32]
Student [sid=4, name=d, sex=女, age=15]
Student [sid=3, name=c, sex=男, age=20]
Student [sid=2, name=b, sex=女, age=11]
Student [sid=1, name=a, sex=男, age=12]

java 对list中对象按属性排序