Reputation: 2566
Imagine you want to transform this:
val initialValues: List<Pair<String, String>>
where the first String represents a key, the second a value
into a map:
val finalMap: Map<String,String>
containing each pair item twice, the first with the original key, the second one with a sort of expanded key.
How would you do that? Currently I'm using a
val finalMap = mutableMapOf<String, String>()
that I use while I'm iterating over initialValues
. But I really don't like it.
initialValues.forEach {
val explodedPairs:List<Pair<String,String>> = <do-something>
explodedPairs.forEach { finalMap.put(it.first, it.second) }
}
how would you do more assertively?
Upvotes: 1
Views: 1542
Reputation: 1180
You could use mapOf
like this:
val initialValues: List<Pair<String, String>> = listOf()
val final = mapOf(*initialValues.toTypedArray())
But @Supriya has the better answer using toMap
Upvotes: 0
Reputation: 1941
You can use associate
/ associateBy
like this -
val map1 = initialList.associate { it.first to it.second }
println(map1.toString()) //{1=x, 2=y}
val map2 = initialList.associateBy({it.first},{it.second})
println(map2.toString()) //{1=x, 2=y}
You can also use toMap
and do this -
val map3 = initialList.toMap()
println(map3.toString()) //{1=x, 2=y}
where this is my initialList declaration -
val initialList = listOf(Pair(1, "x"), Pair(2, "y"))
Upvotes: 5