我有这样的字符串。
val input = "perm1|0,perm2|2,perm2|1"
Run Code Online (Sandbox Code Playgroud)
所需的输出类型是
val output: Set<String, Set<Long>>
Run Code Online (Sandbox Code Playgroud)
和期望的输出值是
{perm1 [], perm2 [1,2] }
Run Code Online (Sandbox Code Playgroud)
如果值为 ,我需要空集0。我使用groupByTo这样的
val output = input.split(",")
.map { it.split("|") }
.groupByTo(
mutableMapOf(),
keySelector = { it[0] },
valueTransform = { it[1].toLong() }
)
Run Code Online (Sandbox Code Playgroud)
然而输出结构是这样的
MutableMap<String, MutableList<Long>>
Run Code Online (Sandbox Code Playgroud)
和输出是
{perm1 [0], perm2 [1,2] }
Run Code Online (Sandbox Code Playgroud)
我正在寻找获得所需输出的最佳方法,而无需使用这样的命令式样式。
val output = mutableMapOf<String, Set<Long>>()
input.split(",").forEach {
val t = it.split("|")
if (t[1].contentEquals("0")) {
output[t[0]] = mutableSetOf()
}
if (output.containsKey(t[0]) && !t[1].contentEquals("0")) {
output[t[0]] = output[t[0]]!! + t[1].toLong()
}
if (!output.containsKey(t[0]) && !t[1].contentEquals("0")) {
output[t[0]] = mutableSetOf()
output[t[0]] = output[t[0]]!! + t[1].toLong()
}
}
Run Code Online (Sandbox Code Playgroud)
您可以简单地使用mapValues将值类型从转换List<Long>为Set<Long>
var res : Map<String, Set<Long>> = input.split(",")
.map { it.split("|") }
.groupBy( {it[0]}, {it[1].toLong()} )
.mapValues { it.value.toSet() }
Run Code Online (Sandbox Code Playgroud)
如果你想0用空集替换列表,你可以使用if-expression
var res : Map<String, Set<Long>> = input.split(",")
.map { it.split("|") }
.groupBy( {it[0]}, {it[1].toLong()} )
.mapValues { if(it.value == listOf<Long>(0)) setOf() else it.value.toSet() }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
136 次 |
| 最近记录: |