废话少说,直接上代码。
一个学生类的实体类
ps:使用IDEA的同学,快捷键[Alt+Insert],可以一键生成对应的set/get/tostring/构造方法。
public class Student {
private Long id;
private String name;
private int age;
private Double height;
public Student(Long id, String name, int age, Double height) {
this.id = id;
this.name = name;
this.age = age;
this.height = height;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", height=" + height +
'}';
}
}
然后我们测试下三种排序方式:
按照id升序排列
按照id逆序排列
按照age排序,然后按照height排序
public class ListStreamSortTest {
public static void main(String[] args) {
// 一个集合中放入4个学生对象
List list = new ArrayList<>();
list.add(new Student(10002L, "ZhangSan", 19, 175.2));
list.add(new Student(10003L, "LiSi", 18, 180.1));
list.add(new Student(10004L, "Peter", 19, 170.8));
list.add(new Student(10001L, "KangKang", 18, 167.4));
// 打印默认顺序
System.out.println("默认顺序:");
list.stream().forEach(System.out::println);
// 按照id排序
System.out.println("id升序:");
list.stream().sorted(Comparator.comparing(Student::getId))
.forEach(System.out::println);
// 按照id逆序排列
System.out.println("id逆序:");
list.stream().sorted(Comparator.comparing(Student::getId).reversed())
.forEach(System.out::println);
// 按照年龄排序,再按照升高排序
System.out.println("age和height排序:");
list.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getHeight))
.forEach(System.out::println);
}
}
执行结果:
默认顺序:
Student{id=10002, name='ZhangSan', age=19, height=175.2}
Student{id=10003, name='LiSi', age=18, height=180.1}
Student{id=10004, name='Peter', age=19, height=170.8}
Student{id=10001, name='KangKang', age=18, height=167.4}
id升序:
Student{id=10001, name='KangKang', age=18, height=167.4}
Student{id=10002, name='ZhangSan', age=19, height=175.2}
Student{id=10003, name='LiSi', age=18, height=180.1}
Student{id=10004, name='Peter', age=19, height=170.8}
id逆序:
Student{id=10004, name='Peter', age=19, height=170.8}
Student{id=10003, name='LiSi', age=18, height=180.1}
Student{id=10002, name='ZhangSan', age=19, height=175.2}
Student{id=10001, name='KangKang', age=18, height=167.4}
age和height排序:
Student{id=10001, name='KangKang', age=18, height=167.4}
Student{id=10003, name='LiSi', age=18, height=180.1}
Student{id=10004, name='Peter', age=19, height=170.8}
Student{id=10002, name='ZhangSan', age=19, height=175.2}
沪漂程序员。 坚持写博客,如果觉得还可以的话,给个小星星哦,你的支持就是我创作的动力。
个人微信公众号:“Java尖子生”,阅读更多干货。
关注公众号,领取学习、面试资料。加技术讨论群。
本文地址:https://blog.csdn.net/Kurry4ever_/article/details/109638154
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!