如何使用java8的stream实现mysql的group by 功能
时间: 2023-11-27 08:50:47 浏览: 172
Java8 Stream学习
可以使用Java 8的Stream API和Collectors.groupingBy()方法实现MySQL的group by功能。假设我们有一个包含以下数据的MySQL表:
```
+----+-------+-------+
| id | name | score |
+----+-------+-------+
| 1 | Alice | 80 |
| 2 | Bob | 75 |
| 3 | Alice | 90 |
| 4 | Bob | 85 |
| 5 | Alice | 95 |
+----+-------+-------+
```
要按name分组并计算每个组的平均分数,可以使用以下代码:
```java
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Stream<Student> students = Stream.of(
new Student(1, "Alice", 80),
new Student(2, "Bob", 75),
new Student(3, "Alice", 90),
new Student(4, "Bob", 85),
new Student(5, "Alice", 95)
);
Map<String, Double> avgScoresByName = students
.collect(Collectors.groupingBy(Student::getName, Collectors.averagingDouble(Student::getScore)));
System.out.println(avgScoresByName);
}
}
class Student {
private int id;
private String name;
private int score;
public Student(int id, String name, int score) {
this.id = id;
this.name = name;
this.score = score;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
}
```
输出结果为:
```
{Alice=88.33333333333333, Bob=80.0}
```
其中,Collectors.groupingBy()方法按照学生的name属性分组,Collectors.averagingDouble()方法计算每个组的平均分数,并返回一个Map<String, Double>对象,其中键为name,值为平均分数。
阅读全文