Using Kotlin, how would I transform a Sequence
of detail objects into a Sequence
of summary objects, where each summary object represents a fixed number of detailed objects? It's kind of like map
, except it's not one-to-one and it's kind of like reduce
except it's not to a single accumulator?
For example:
var hourlyInfo: Sequence<HourlyData> = ...
var dailyInfo: Sequence<DailySummary> = hourlyInfo.somethingMagical()
What about the same problem with a stream instead of a sequence?
CodePudding user response:
If there's a known fixed number of items, you use chunked
and then map. When the sequence is iterated, actual lists of each chunk of items will be allocated.
var dailyInfo: Sequence<DailySummary> = hourlyInfo
.chunked(12)
.map(::DailySummary) // for example if it has a constructor taking a List of 12 HourlyData
If the List of HourlyData isn't ordered, or there isn't some fixed size, then I suppose you have to group by some property in HourlyData and then map it. This does not preserve Sequence status.
var dailyInfo: Sequence<DailySummary> = hourlyInfo
.groupBy(HourlyData::hourOfDay)
.map { (hour, listOfHourlyData) -> DailySummary(hour, listOfHourlyData) }