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?
Convert Stream into List using List. stream() method.
Streams don't change the original data structure, they only provide the result as per the pipelined methods. Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With