Java对象排序两种方法

转载:https://blog.csdn.net/wangtaocsdn/article/details/71500500

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

方法一:将要排序的对象类实现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);
}
}
}

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

猜你喜欢

转载自www.cnblogs.com/ConfidentLiu/p/10410080.html