Is there an easy way to create a view of multiple ...
# announcements
r
Is there an easy way to create a view of multiple lists? Like, I would like to be able to iterate over "list" A to iterate over lists B, C and D, without it being an actual separate collection, just a view. Without building my own iterators and stuff, I just want to know if there's another cool thing in the stdlib I don't know about
s
what exactly are you trying to do
oh, I see, you want to iterate over multiple lists using one view
r
Trying to hide/abstract the fact that I have multiple lists of slightly different items being a single list of interface-implmenting items basically
I don't want to pass lists of lists around for no reason, and I just wanted to check that there was no dead simple way to do what I want before doing it myself
r
This should do the job:
Copy code
val b = listOf("b")
val c = listOf("c")
val d = listOf("d")
val a = b.asSequence() + c + d
☝️ 1
The resulting sequence will iterate all the backing lists in order when iterated.
...without creating any additional lists.
r
Right, a Sequence, like an Iterator, is basically a view
k
@ribesg plain ol’ Java has
Stream.concat
Kotlin has
sequenceOf(...)
scratch that, not what you want. Robin was onto it though.
a
you can use
buildSequence
(https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/build-sequence.html):
Copy code
val sequence = buildSequence {
        for (subList in lists) {
            yieldAll(subList)
        }
    }
r
That works, too, but in my opinion is less easy to understand when reading.
k
sequenceOf(listA, listB, listC).flatMap { it.asSequence() }