我有一个Java POJO,它具有LocalDateTime字段(controlDate)和一个int(订单)字段以及其他字段,但与我的问题无关。
我从数据库中获取了该POJO的列表,例如:
controlDate orders
2018-10-07 23:26:00.000+02 5
2018-10-07 23:27:00.000+02 2
2018-10-07 18:33:00.000+02 8
2018-10-07 18:35:00.000+02 4
我的最终目标是按n小时的数据包汇总数据(并以最早的日期作为汇总日期),并获取“订单”列的平均值
例如,值为n = 2,我想得到类似这样的东西:
controlDate orders
2018-10-07 23:26:00.000+02 3 (or 4, I don't really care about the rounding)
2018-10-07 18:33:00.000+02 6
我非常确定,使用Java 8流可以实现此目标,也许可以使用Collectors.groupingBy,但是我不知道该如何实现。...
感谢您的帮助!
答案 0 :(得分:1)
此代码应能解决问题:
class Delivery {
LocalDateTime timestamp;
Integer packages;
public Delivery(LocalDateTime timestamp, Integer packages) {
this.timestamp = timestamp;
this.packages = packages;
}
public Integer getPackages() {
return packages;
}
public LocalDate getDate() {
return timestamp.toLocalDate();
}
public Integer getHour() {
return timestamp.getHour();
}
}
public class Calculate {
public static void main(final String[] args) {
Stream<Delivery> deliveries = Stream.of(
new Delivery(LocalDateTime.of(2018, 10, 7, 23, 26), 5),
new Delivery(LocalDateTime.of(2018, 10, 7, 23, 27), 2),
new Delivery(LocalDateTime.of(2018, 10, 7, 18, 33), 8),
new Delivery(LocalDateTime.of(2018, 10, 7, 18, 35), 4)
);
deliveries.map(delivery -> {
Map r = new HashMap();
r.put(delivery.getHour(), delivery.getPackages());
return r;
}).collect(Collectors.groupingBy(d -> d.keySet().toArray()[0])).forEach((o, packages) -> {
System.out.print(o + ":");
Integer sum = (Integer) packages.stream().map(map -> map.get(o)).reduce(0, (a, b) -> (Integer) a + (Integer) b);
long count = packages.stream().count();
System.out.println(sum / count);
});
}
}
您将获得:
18:6
23:3
它是按小时排序的,因此您可以扩展此解决方案以满足您的需求。