Android Kotlin: map or other equivalent of converting a List to a List of Pairs?

Suppose I have this:

listOf("ball","apple","zebra","cat")

I want to convert this to:

listOf(Pair("ball","b"),Pair("apple","a"),Pair("zebra","z"),Pair("cat","c"))

Basically I want the second of the Pair to be a value computed using the array value.

I realize I can create this using some combinations of a for loop. But is there a built in way using some function similar to map which does this?

Upvotes: 0

Views: 356

Answers (1)

Ravi Kumar
Ravi Kumar

Reputation: 4528

You can do it like:

 val mylist = listOf("ball","apple","zebra","cat")
 val pairList = mylist.map{
       Pair(it, it[0])
   }
 print(pairList)

Upvotes: 3

Related Questions