Kotlin Map.mapTo到另一个映射
我想将Kotlin Map.mapTo到另一个映射,kotlin,Kotlin,我想将map映射到map,但无法返回map。map函数中的条目: itemsWithQuantity.mapTo(mutableMapOf<String, Boolean>(), { it.key.toString() to it.value != 0 }) itemsWithQuantity.mapTo(mutableMapOf(),{it.key.toString()to it.value!=0}) (当然我使用的是更复杂的映射函数,但没关系,问题是一样的) 上面说 Muta
map
映射到map
,但无法返回map。map函数中的条目:
itemsWithQuantity.mapTo(mutableMapOf<String, Boolean>(), { it.key.toString() to it.value != 0 })
itemsWithQuantity.mapTo(mutableMapOf(),{it.key.toString()to it.value!=0})
(当然我使用的是更复杂的映射函数,但没关系,问题是一样的)
上面说
MutableMap<String, Boolean> is not a subtype of MutableCollection<Pair<String, Boolean>>.
MutableMap不是MutableCollection的子类型。
那么如何返回Map.Entry而不是Pair
现在我这样做:
val detailsIds = mutableMapOf<String, Boolean>()
itemsWithQuantity.forEach { item, quantity -> detailsIds.put(it.key.toString(), it.value != 0) }
val detailsIds=mutableMapOf()
itemsWithQuantity.forEach{item,quantity->detailsIds.put(it.key.toString(),it.value!=0)}
但是我想用mapTo来代替:
xs.associateTo(mutableMapOf(),{“${it.key}”到(it.value!=0)})
另外,请注意it.value!=0
与类似,该函数不将结果收集到
映射中,而是与集合一起使用,希望您提供一个可变集合
关联,以便仅与集合(您的xs)一起使用。如果xs是一个映射,那么这就不起作用了。
xs.associateTo(mutableMapOf<String, Boolean>(), { "${it.key}" to (it.value != 0) })