list集合根据jsonobjectvalue排序_Java8使⽤stream().sor。
。。
集合对像定义
集合对象以学⽣类(StudentInfo)为例,有学⽣的基本信息,包括:姓名,性别,年龄,⾝⾼,⽣⽇⼏项。
使⽤stream().sorted()进⾏排序,需要该类实现 Comparable 接⼝,该接⼝只有⼀个⽅法需要实现,如下:
publicintcompareTo(T o);
有关compareTo⽅法的实现说明,请参考:Java 关于重写compareTo⽅法
我的学⽣类代码如下:
StudentInfo对象类
添加测试数据
java stream下⾯来添加⼀些测试⽤的数据,代码如下:
//测试数据,请不要纠结数据的严谨性List studentList =newArrayList<>();
studentList.add(newStudentInfo("李⼩明",true,18,1.76,LocalDate.of(2001,3,23)));
studentList.add(newStudentInfo("张⼩丽",false,18,1.61,LocalDate.of(2001,6,3)));
studentList.add(newStudentInfo("王⼤朋",true,19,1.82,LocalDate.of(2000,3,11)));
studentList.add(newStudentInfo("陈⼩跑",false,17,1.67,LocalDate.of(2002,10,18)));
排序
使⽤年龄进⾏升序排序
//排序前输出StudentInfo.printStudents(studentList);//按年龄排序(Integer类型)List studentsSortName =
studentList.stream().sorted(Comparatorparing(StudentInfo::getAge)).List());//排序后输出StudentInfo.printStudents(studentsSortName);
结果如下图:
使⽤年龄进⾏降序排序(使⽤reversed()⽅法)
//排序前输出StudentInfo.printStudents(studentList);//按年龄排序(Integer类型)List studentsSortName =
studentList.stream().sorted(Comparatorparing(StudentInfo::getAge).reversed()).List());//排序后输出StudentInfo.printStudents(studentsSortName);
结果如下图:
使⽤年龄进⾏降序排序,年龄相同再使⽤⾝⾼升序排序
//排序前输出 StudentInfo.printStudents(studentList);
//按年龄排序(Integer类型)List studentsSortName = studentList.stream()
.sorted(Comparatorparing(StudentInfo::getAge).reversed().thenComparing(StudentInfo::getHeight)) .List());
//排序后输出StudentInfo.printStudents(studentsSortName);
结果如下图: