Is there a way to "expand" a list of objects into a larger list using the stream API?

Consider this example: I have a RangeSet that contains, for example, timestamps. I want to get the total duration of ranges using java8 threads instead of the imperative way:

// "list" is List<RangeSet<Long>>

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

"Extension", of course, does not exist; the idea is that it converts each individual object into a stream into a list of other objects and adds this list to the resulting stream.

Is there something similar or another way to do this smoothly?

+4
source share
1 answer

Looks like you're just looking Stream.flatMapfor example

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

All Articles