I am processing input data that comes in "alternating" lines.
In order to handle that nicely, I (and SO) came up with this code:
val foobars = mutableListOf<FooBar>()
lines.chunked(2) { (l1, l2) ->
foobars.add( FooBar( generateFoo(l1), generateBar(l2) )
}
The above works, but it seems a bit odd to first create that empty list, and to then append to it in order to "collect" the freshly created objects.
If this would be a Java stream, the "collecting" part would be straight forward, using a List collector.
Now I am wondering if there is more elegant/canonical way of collecting my list items in kotlin?
It's actually simpler then you think, e.g.
val foobars = lines.chunked(2) { (l1, l2) ->
FooBar( generateFoo(l1), generateBar(l2) )
}.toMutableList()
The difference to a Java stream is, that you can actually operate on a list (/sequence/iterable) directly and you get a new one in return every time you call something like chunked
, filter
, map
, toList
, toMutableList
, etc. So after calling chunked
(+ transformation) you got a new list containing the transformations. You then can transform it to a (new) mutable list just by calling toMutableList()
.
And if you do not need to alter the list later, you can just skip toMutableList()
and you have your list already.