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

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

The "expand" of course doesn't exist ; the idea is it would convert each single object in the stream to a list of other objects, and add that list to the resulting stream.

Is there something similar, or another way to do it fluently?

Jon Skeet
people
quotationmark

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

people

See more on this question at Stackoverflow