import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestUtil {
public static void main(String[] args) {
Student stu1 = new Student("小米", 1);
Student stu2 = new Student("小王", 2);
Student stu3 = new Student("小明", 3);
List<Student> list = new ArrayList<>();
list.add(stu2);
list.add(stu1);
list.add(stu3);
System.out.println("排序前:");
System.out.println(list);
System.out.println("排序后:");
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student stu1, Student stu2) {
return stu1.getAge() - stu2.getAge();
}
});
System.out.println(list);
}
}
简写方式:
list.sort((l1,l2) -> l1-l2);