java 8 steam groupby 使用示例
时间: 2023-10-24 13:05:40 浏览: 159
假设我们有一个Student类,包含姓名、年龄和成绩等属性,我们需要按照年龄分组,然后统计每个年龄段的人数和总成绩。
我们可以使用Java 8的Stream API中的groupBy方法来实现这个需求。具体示例代码如下:
```java
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Student {
private String name;
private int age;
private int score;
public Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getScore() {
return score;
}
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("Alice", 18, 90),
new Student("Bob", 19, 80),
new Student("Charlie", 18, 95),
new Student("David", 19, 85),
new Student("Ella", 20, 92),
new Student("Frank", 20, 88)
);
Map<Integer, List<Student>> groupByAge = students.stream()
.collect(Collectors.groupingBy(Student::getAge));
Map<Integer, Integer> countByAge = groupByAge.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().size()
));
Map<Integer, Integer> sumByAge = groupByAge.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().stream().mapToInt(Student::getScore).sum()
));
System.out.println("Group by age: " + groupByAge);
System.out.println("Count by age: " + countByAge);
System.out.println("Sum by age: " + sumByAge);
}
}
```
运行结果如下:
```
Group by age: {18=[Student{name='Alice', age=18, score=90}, Student{name='Charlie', age=18, score=95}], 19=[Student{name='Bob', age=19, score=80}, Student{name='David', age=19, score=85}], 20=[Student{name='Ella', age=20, score=92}, Student{name='Frank', age=20, score=88}]}
Count by age: {18=2, 19=2, 20=2}
Sum by age: {18=185, 19=165, 20=180}
```
从运行结果可以看出,我们成功地按照年龄分组,并统计了每个年龄段的人数和总成绩。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)