使用 Collectors.summingInt 时如何获取自定义类型而不是 Integer?

How to get a custom type instead of Integer when using Collectors.summingInt?

我目前正在创建这样的 Map<String, Map<LocalDate, Integer>>,其中 Integer 代表秒数:

Map<String, Map<LocalDate, Integer>> map = stream.collect(Collectors.groupingBy(
            x -> x.getProject(),
            Collectors.groupingBy(
                x -> x.getDate(),
                Collectors.summingInt(t -> t.getDuration().toSecondOfDay())
            )
        ));

我怎样才能创建 Map<String, Map<LocalDate, Duration>>

要将 IntegerCollectors.summingInt 更改为 Duration,您只需将 Collector 替换为:

Collectors.collectingAndThen(
    Collectors.summingInt(t -> t.getDuration().toSecondOfDay()),
    Duration::ofSeconds
)

如果您对 getDuration() 使用实际的 Duration(而不是 LocalTime),您也可以直接对 Duration 求和,如下所示:

Map<String, Map<LocalDate, Duration>> map = stream.collect(Collectors.groupingBy(
        MyObject::getProject,
        Collectors.groupingBy(
                MyObject::getDate,
                Collectors.mapping(MyObject::getDuration,
                        Collectors.reducing(Duration.ZERO, Duration::plus))
        )
));

优点是它还对纳秒求和,并且也可以推广到其他类型。

但请注意,它会创建许多中间 Duration 实例,这可能会对性能产生影响。