嗨,我正在处理下一个代码:
private fun getAttributesMap(navMenu: NavItem?): AttributesMap {
var attributesString = navMenu?.attributes
val attributesMap = mutableMapOf<String, String>()
attributesString?.lines()?.map {
val pair = it.split("=")
if (pair?.size == 2) {
attributesMap.put(pair[0], pair[1])
}
}
return AttributesMap(attributesMap)
}
但是根据文档https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map.html
我应该能够将这种转换的结果分配给attributesMap。关于kotlin .map方法会有什么线索?
谢谢!
答案 0 :(得分:1)
将map
和filter
组合使用:
val attributesMap = attributesString.lines()
.map { it.split("=") }
.filter { it.size == 2 } //filter all with more or less elements
.map { it[0] to it[1] } //convert to Pair
.toMap() //convert to Map