Java对对象按照其属性排序的两种方法

来源:互联网 发布:网络消费者投诉来分期 编辑:程序博客网 时间:2024/05/22 03:30

转载请标明出处:http://blog.csdn.net/wangtaocsdn/article/details/71500500

有时候需要对对象列表或数组进行排序,下面提供两种简单方式:

方法一:将要排序的对象类实现Comparable<>接口。

首先,创建学生类,我们将根据学生成绩对学生进行排序:

public class Test {    public static void main(String[] args) {        // TODO Auto-generated method stub        ArrayList<Student> students = new ArrayList<>();        students.add(new Student("大铭", 19, 89));        students.add(new Student("来福", 26, 90));        students.add(new Student("仓颉", 23, 70));        students.add(new Student("王磊", 18, 80));        System.out.println("排序前:");        for (Student student : students) {            System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);        }        // 排序        Collections.sort(students);        System.out.println("排序后:");        for (Student student : students) {            System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);        }    }}class Student implements Comparable<Student>{    String name;    int age;    int score;    public Student(String name, int age,int score) {        this.name = name;        this.age = age;        this.score = score;    }    @Override    public int compareTo(Studento) {        // TODO Auto-generated method stub        return this.age - o.age;    }}

同理,也可以根据对象的其他属性进行排序。

方法二:使用Comparator匿名内部类实现。

还是使用同一个例子,按成绩将学生排序:

public class Test {    public static void main(String[] args) {        // TODO Auto-generated method stub        ArrayList<Student> students = new ArrayList<>();        students.add(new Student("大铭", 19, 89));        students.add(new Student("来福", 26, 90));        students.add(new Student("仓颉", 23, 70));        students.add(new Student("王磊", 18, 80));        System.out.println("排序前:");        for (Student student : students) {            System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);        }//      Collections.sort(students,new Comparator<Object>() {//      });        Collections.sort(students,new Comparator<Student>() {            @Override            public int compare(Student o1, Student o2) {                // TODO Auto-generated method stub                return o1.age-o2.age;            }        });        System.out.println("排序后:");        for (Student student : students) {            System.out.println("姓名:"+student.name+" 年龄:"+student.age+" 成绩:"+student.score);        }    }}class Student {    String name;    int age;    int score;    public Student(String name, int age,int score) {        this.name = name;        this.age = age;        this.score = score;    }}

也可以实现按对象属性将对象列表排序。

1 0