list stream 多条件排序
时间: 2023-07-22 11:16:38 浏览: 48
在Java中使用Stream对list进行多条件排序可以使用`sorted()`方法,结合`Comparator`接口的`thenComparing()`方法实现。以下是一个示例代码:
假设我们有一个`Person`对象,其中包含姓名、年龄和薪水属性:
```java
public class Person {
private String name;
private int age;
private double salary;
// 省略构造方法和 getter/setter 方法
}
```
现在我们有一个`List<Person>`,需要按照年龄升序、薪水降序、姓名升序的顺序进行排序,代码如下:
```java
List<Person> persons = new ArrayList<>();
persons.add(new Person("Bob", 30, 5000.0));
persons.add(new Person("Alice", 25, 6000.0));
persons.add(new Person("John", 30, 4500.0));
persons.add(new Person("Tom", 20, 8000.0));
List<Person> sortedPersons = persons.stream()
.sorted(Comparator.comparingInt(Person::getAge) // 按照年龄升序
.thenComparingDouble(Person::getSalary).reversed() // 薪水降序
.thenComparing(Person::getName)) // 姓名升序
.collect(Collectors.toList());
```
首先使用`Comparator.comparingInt()`方法按照年龄升序排序,然后使用`thenComparingDouble().reversed()`方法按照薪水降序排序,最后使用`thenComparing()`方法按照姓名升序排序。最终使用`collect()`方法将排序后的结果收集到一个新的`List`中。