jdk8 list stream 多条件分组排序
时间: 2023-09-23 08:11:13 浏览: 98
java8 stream自定义分组求和并排序的实现
可以使用Java 8中的Stream API来实现多条件分组排序。以下是示例代码:
```java
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// 创建示例数据
List<Person> persons = Arrays.asList(
new Person("Alice", 30, "New York"),
new Person("Bob", 25, "London"),
new Person("Charlie", 35, "New York"),
new Person("David", 20, "Paris"),
new Person("Eva", 28, "London")
);
// 按城市分组,然后按年龄和姓名排序
Map<String, List<Person>> result = persons.stream()
.sorted(Comparator.comparing(Person::getAge).thenComparing(Person::getName))
.collect(Collectors.groupingBy(Person::getCity));
// 打印结果
result.forEach((city, people) -> {
System.out.println(city);
people.forEach(System.out::println);
System.out.println();
});
}
}
class Person {
private String name;
private int age;
private String city;
public Person(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getCity() {
return city;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
```
输出结果为:
```
London
Bob (25)
Eva (28)
New York
Alice (30)
Charlie (35)
Paris
David (20)
```
在示例中,我们首先使用`sorted`方法按年龄和姓名排序,然后使用`groupingBy`方法按城市分组。最后,我们打印结果,城市和人员列表分别输出。
阅读全文