Is there a functional/idiomatic Kotlin way to crea...
# getting-started
d
Is there a functional/idiomatic Kotlin way to create a list from a map where the value of each element is repeated the number of times as the key? For instance,
{3=7, 2=8, 4=1}
turns into
[7, 7, 7, 8, 8, 1, 1, 1, 1]
? My naive way is to create a
mutableList
and iterate through the map using
forEach
and `repeat`edly
add
items to the list.
👀 1
g
Copy code
val map = mapOf(3 to 7, 2 to 8, 4 to 1)

map.flatMap { (key, value) -> List(key) { value} }
this returns
Copy code
[7, 7, 7, 8, 8, 1, 1, 1, 1]
K 10
d
thanks!
flatMap
was the key piece I was missing.
Curious: since the final list could get quite large, and I only need the first n elements, is there a way to stop the generation of the
flatMap
once I've reached a list of size n?
v
Writing from the top of my head, so could be wrong. But I think if you make a sequence first and then use
take(n)
, it should probably work.
d
Thank you @CLOVIS! - so if I do
take(4).forEach{ println("Result: $it") }
then the sequence will only produce 4 elements?
j
Yes, that's what sequences are for - they are lazy. Elements are produced and processed only when necessary for the end of the pipeline.
gratitude thank you 1
c
When learning about this, don't hesitate to add
.onEach { println("$it") }
in the middle of the pipeline to see when elements are generated :)
🆒 1