If I have a `List<List<T>>`, is there a way to flatten it while adding items at the boun...
r
If I have a
List<List<T>>
, is there a way to flatten it while adding items at the boundaries between the lists?
k
You don't want items at the end?
r
The idea is if I have something like this
Copy code
val list = listOf(
        listOf("a", "b", "c"),
        listOf("d", "e", "f")
)
and I call this imaginary function, say the joining element is "|", I want it to return
listOf("a", "b", "c", "|", "d", "e", "f")
k
Terrible performance:
list.reduce { acc, list -> acc + "|" + list }
k
Would a reduction suffice here?
Copy code
val list = listOf(
            listOf("a", "b", "c"),
            listOf("d", "e", "f")
    )

    println(list.reduce { a, b -> a + "|" + b })
r
Ah, yeah that works. Thanks
k
I wouldn't do it though, just write a quick extension function on the side somewhere.
r
Do reductions like that incur a performance cost that would be noticable?
k
Yeah, this creates 2 temporary lists per join that happens.
r
The only other solution that I could think of is worse
Though the time measurements are in ns, measureTimeMillis just spat out 0
Working on the example i gave above
k
Sure, for small inputs like this performance is pretty much irrelevant.