Java实现对象按照其属性排序的两种方法示例
LIFE_R 人气:1本文实例讲述了Java实现对象按照其属性排序的两种方法。分享给大家供大家参考,具体如下:
有时候需要对对象列表或数组进行排序,下面提供两种简单方式:
方法一:将要排序的对象类实现Comparable<>接口。
首先,创建学生类,我们将根据学生成绩对学生进行排序:
/** * 学生类 */ 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; } }
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); } } }
同理,也可以根据对象的其他属性进行排序。
方法二:使用Comparator匿名内部类实现。
还是使用同一个例子,按成绩将学生排序:
/** * 学生类 */ 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; } }
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<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); } } }
也可以实现按对象属性将对象列表排序。
希望本文所述对大家java程序设计有所帮助。
加载全部内容