可以使用Comparator接口来指定排序方式,然后使用sorted方法进行排序。

假设有一个Person类,其中有一个age属性,我们要根据age属性进行倒序排序,可以这样写:

List<Person> persons = new ArrayList<>();
// 添加Person对象到List中
// ...

List<Person> sortedPersons = persons.stream()
        .sorted(Comparator.comparingInt(Person::getAge).reversed())
        .collect(Collectors.toList());

上述代码中,Comparator.comparingInt(Person::getAge)指定了按照age属性进行排序,reversed()方法表示倒序排序。最后使用collect方法将排序后的结果收集到一个新的List中。

java stream sorted 根据对象某个属性 倒序

原文地址: https://www.cveoy.top/t/topic/fpty 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录