废话不多说,直接上代码:
public class Student {
public String name;
public int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class domeTest {
public static void main(String[] args) {
List<Student> stu1 = new ArrayList<Student>();
stu1.add(new Student("一", 3));
stu1.add(new Student("二", 1));
stu1.add(new Student("三", 2));
stu1.add(new Student("五", 5));
stu1.add(new Student("四", 4));
//升序
Collections.sort(stu1, Comparator.comparing(Student::getAge));
for (Student student : stu1) {
System.out.println("姓名:" + student.getName() + " 年龄:" + student.getAge());
}
//降序
Collections.sort(stu1, Comparator.comparing(Student::getAge).reversed());
for (Student student : stu1) {
System.out.println("姓名:" + student.getName() + " 年龄:" + student.getAge());
continue;
}
//从大到小排序
List<Student> li = stu1.stream()
.sorted((x, y) -> {
if (x.getAge().equals(y.getAge())) {
return 0;
} else {
return x.getAge() > y.getAge() ? -1 : 1;
}
}
)
.collect(Collectors.toList());
li.forEach(s->{
System.out.println(s.getAge());
});
}
}