java中对list的排序
话不多说直接贴代码
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class H1 {
public static void main(String[] args) {
// 先定义五个学生的变量
Student st1 = new Student("Bob",18);
Student st2 = new Student("Linda",20);
Student st3 = new Student("Rose",12);
Student st4 = new Student("Aana",14);
Student st5 = new Student("Bill",18);
List<Student> list = new ArrayList<Student>();
list.add(st1);
list.add(st2);
list.add(st3);
list.add(st4);
list.add(st5);
list.sort(new Comparator<Student>() {
//根据学生的年龄进行降序排列
@Override
public int compare(Student o1, Student o2) {
if(o1.getAge()>o2.getAge()) {
return -1;
}else if(o1.getAge()==o2.getAge()) {
//如果学生年龄相同,则根据姓名进行降序排列
if(o1.getName().compareTo(o2.getName())==1) {
return -1;
}
return 1;
}else {
return 1;
}
}
});
for(Student s : list) {
//输出学生信息
System.out.println(s.toString());
}
}
}
/**
*定义一个学生类
*/
public class Student {
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//重写toString方法
@Override
public String toString() {
// TODO Auto-generated method stub
return name+"---"+age;
}
}
。