Ian Rehwinkel
Ian Rehwinkel

Reputation: 2615

Mapping an iterable 1-to-n in kotlin

What I am trying to do is use the Iterable.map but instead of transforming every one value to one new value, I want to transform one value to multiple new values.

For example:

val myList = listOf("test", "123", "another.test", "test2")
val result = myList.map {
    if(it.contains(".")) {
        return@map it.split(".")
    } else {
        return@map it
    }
}
//desired output: ["test", "123", "another", "test", "test2"]

This code would result in a List which contains both strings and lists of strings (type Any).

How could I most elegantly implement this?

Upvotes: 1

Views: 865

Answers (1)

Laksitha Ranasingha
Laksitha Ranasingha

Reputation: 4507

One quick way to do this is using flatMap.

val output = myList.flatMap { if(it.contains(".")) it.split(".") else listOf(it) }

The flatMap method transforms the each element using given function and then flatten the result to a single list.

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/flat-map.html

Upvotes: 2

Related Questions