[英]Java/Kotlin - convert Set to Map<Long, Set<Long>>
我有一组长值
Set<Long> ids = {1,2,3,4}
我想要实现的是
Set<Map<Long, Set<Long>>
从这组 ids 中,我需要有 4 个元素的 Set,例如:
Set: {
Map -> key: 1, values: 2,3,4
Map -> key: 2, values: 1,3,4
Map -> key: 3, values: 1,2,4
Map -> key: 4, values: 1,2,3
}
我怎样才能通过stream
或者 kotlin 的groupBy
获得它?
有人会有这样的 map 吗? (没有for
或while
循环的解决方案)
您可以使用map
方法将每个元素转换为Map
然后收集它来set
var set = setOf(1, 2, 3, 4)
var map = set.map { v -> mapOf(v to set.toMutableSet().filter { it != v }.toSet()) }
.toSet()
但是,由于性能或可读性,我不认为它比简单的foreach
循环好得多
这将是一个带有 for 循环的可能解决方案:
val ids: Set<Long> = setOf(1, 2, 3, 4)
var result: MutableSet<Map<Long, Set<Long>>> = mutableSetOf()
for ((index, _) in ids.withIndex()) {
result.add(
mapOf(ids.elementAt(index) to ids.filter { it != ids.elementAt(index) }.toSet() )
)
}
println(result)
关于
groupBy
的意见By
请注意, groupBy
可以将原始集合拆分为多个没有交集的集合。 所以不可能直接用groupBy
function 构造上面提到的 map。
下面的解决方案在获取result
时利用了groupBy
,但是result2
更易于阅读并且符合直觉:
fun main() {
val set = setOf(1, 2, 3, 4)
val result = set
.groupBy { it }
.mapValues { (_, values) -> set.filter { it !in values } }
println(result) // {1=[2, 3, 4], 2=[1, 3, 4], 3=[1, 2, 4], 4=[1, 2, 3]}
val result2 = HashMap<Int, List<Int>>().apply {
set.forEach { this[it] = (set - it).toList() }
}
println(result2) // {1=[2, 3, 4], 2=[1, 3, 4], 3=[1, 2, 4], 4=[1, 2, 3]}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.