Home > database >  How to push results from map to multiple list in Kotlin?
How to push results from map to multiple list in Kotlin?

Time:10-19

I have the same operation from two list and want to put them in one map function rather than two.

        val messages1 = list.map {
            spConverter.mapToSppmFromPs(it)
        }
        val messages2 = list.map {
            spConverter.mapToSpFromPs(it)
        } 

Is there a way to put this two operation into one map?

CodePudding user response:

The map function can only create one list, so you can't have it create messages1 and messages2 which are two lists. Perhaps this code will suit:

val (messages1, messages2) = list
    .map { Pair(spConverter.mapToSppmFromPs(it), spConverter.mapToSpFromPs(it)) }
    .unzip()

First, the map function creates a list of pairs, and then the unzip function runs over that list and creates the two lists that you want.

Unless your list is actually something that can only be iterated once, I would prefer your original code.

CodePudding user response:

Well, not really.

.map returns ONE result. So yes, you could have:

    val messages1 = mutableListOf()
    val messages2 = list.map {
        messages1.add(spConverter.mapToSppmFromPs(it))
        spConverter.mapToSpFromPs(it)
    }
    

But that is just ugly. I think running forEach somewhere in the code will be better.

CodePudding user response:

If you make a list of the functions you want to apply, you can loop over that list and apply each function to the list in turn. With a destructuring declaration you can separate the resulting list of lists into two variables.

val functions = listOf(spConverter::mapToSppmFromPs, spConverter::mapToSpFromPs)
val (messages1, messages2) = functions.map { f -> 
    list.map { f(it) }
}
  • Related