import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class StudentComparator
implements Comparator<Student> {
public int compare(Student o1, Student o2) {
return (o1.getAge() < o2.getAge() ? -1 : (o1.getAge() == o2.getAge() ? 0 : 1));
}
}
public class testSort {
public static void main(String[] args) {
Student stu1 = new Student("zhangsan", 13);
Student stu2 = new Student("lisi", 11);
Student stu3 = new Student("wangba", 31);
Student stu4 = new Student("zhaoliu", 36);
List<Student> stu = new ArrayList<Student>();
stu.add(stu1);
stu.add(stu2);
stu.add(stu3);
stu.add(stu4);
System.out.println("原始数据:");
for (Student student : stu) {
System.out.println(student.getAge());
}
System.out.println("进行排序......");
StudentComparator studentComparator = new StudentComparator();
Collections.sort(stu, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return (o1.getAge() < o2.getAge() ? -1 : (o1.getAge() == o2.getAge() ? 0 : 1));
}
});
for (Student student : stu) {
System.out.println(student.getAge());
}
Student maxstu = Collections.max(stu, studentComparator);
System.out.println("--" + maxstu.getName());
}
}
List结果集排序
最新推荐文章于 2024-04-17 18:48:32 发布