Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-8

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?

like image 257
Joel Avatar asked Feb 26 '15 11:02

Joel


People also ask

Which method is used to convert stream to List?

Convert Stream into List using List. stream() method.

Do streams modify original List?

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.


1 Answers

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);
like image 62
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet