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

我与影子孤独终老i 提交于 2020-01-02 01:05:14

问题


I am currently creating a Map<String, Map<LocalDate, Integer>> like this, where the Integer represents seconds:

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

How could I instead create a Map<String, Map<LocalDate, Duration>>?


回答1:


To change that Integer from Collectors.summingInt to a Duration, you simply need to replace that Collector with:

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



回答2:


If you were using an actual Duration for getDuration() (instead of LocalTime), you could also sum directly the Duration's as follows:

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))
        )
));

With the advantage that it also sums the nanoseconds, and could be generalized to other types as well.

Note however that it creates many intermediate Duration instances which could have an impact on the performance.



来源:https://stackoverflow.com/questions/44285623/how-to-get-a-custom-type-instead-of-integer-when-using-collectors-summingint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!