Is there a way to “expand” a list of objects into a bigger list with stream API?

前端 未结 1 592
太阳男子
太阳男子 2021-02-08 20:16

Consider this example: I have a list of RangeSet that contains, for instance, timestamps. I want to get the total duration of ranges using java8 streams instead of the imperativ

1条回答
  •  走了就别回头了
    2021-02-08 20:51

    It looks like you're just looking for Stream.flatMap, e.g.

    long totalTime = list.stream()
        .flatMap(rangeset -> rangeset.asRanges().stream())
        .map(range -> range.upperEndpoint() - range.lowerEndpoint())
        .reduce(0, (total, time) -> total + time);
    

    0 讨论(0)
提交回复
热议问题