Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map.mapTo to another map

Tags:

kotlin

I want to map Map<DAO, Int> to Map<String, Boolean> but I can't return Map.Entry in map function:

itemsWithQuantity.mapTo(mutableMapOf<String, Boolean>(), { it.key.toString() to it.value != 0 })

(of course I am using more complex mapping function, but it doesn't matter, problem is same)

It says

MutableMap<String, Boolean> is not a subtype of MutableCollection<Pair<String, Boolean>>.

So how can I return Map.Entry instead of Pair?

Now I am doing it this way:

val detailsIds = mutableMapOf<String, Boolean>()
itemsWithQuantity.forEach { item, quantity -> detailsIds.put(it.key.toString(), it.value != 0) }

But I want to use mapTo

like image 301
Viktor Sinelnikov Avatar asked Mar 13 '17 16:03

Viktor Sinelnikov


1 Answers

Use associateTo instead:

xs.associateTo(mutableMapOf<String, Boolean>(), { "${it.key}" to (it.value != 0) })

Also, note the brackets around it.value != 0.

The mapTo function, similarly to map, doesn't collect the results into a Map, but instead works with a Collection, expecting you to provide a MutableCollection<Pair<String, Boolean>>.

like image 183
hotkey Avatar answered Oct 02 '22 17:10

hotkey