问:学生集合需要先按age倒排,相同年龄的再按生日倒排,选哪个?
A:
studentInfo = studentInfo.stream().sorted(Comparator.comparing(StudentInfo::getAge).reversed().thenComparing(StudentInfo::getBirthday).reversed()).collect(Collectors.toList());
B:
studentInfo = studentInfo.stream().sorted(Comparator.comparing(StudentInfo::getAge).thenComparing(StudentInfo::getBirthday).reversed()).collect(Collectors.toList());
C:
studentInfo = studentInfo.stream().sorted(Comparator.comparing(StudentInfo::getAge, Comparator.reverseOrder()).thenComparing(StudentInfo::getBirthday,Comparator.reverseOrder())).collect(Collectors.toList());
D:
studentInfo = studentInfo.stream().sorted(Comparator.comparing(StudentInfo::getAge).thenComparing(StudentInfo::getBirthday,Comparator.reverseOrder())).collect(Collectors.toList());
正确答案:
B 和 C
分析:
A:年龄和生日都reversed(),我理解的是先按年龄倒排再按生日倒排,结果并不是这样,结果错误,生日reversed()会使左边所有排序反转,导致年龄并不是倒序排列。
B:只在生日后加reversed(),结果正确,原因同上,年龄先正序排,生日reversed()后整个排序反转,正好年龄倒序
C:年龄和生日都Comparator.reverseOrder(),结果正确,因为Comparator.reverseOrder()只针对当前属性的倒排
D:只在生日后加Comparator.reverseOrder(),结果错误,年龄正排,生日倒排
注意reversed()和Comparator.reverseOrder()的使用,表面上看到的和实际还是有出入的
- Comparator.comparing(类::属性一).reversed();
- Comparator.comparing(类::属性一,Comparator.reverseOrder());
两种排序是完全不一样的,一定要区分开, reversed()是得到排序结果后再排序,Comparator.reverseOrder()是直接进行排序,理解错误很容易出现混淆,相比较而言Comparator.reverseOrder()更好理解。