繁体   English   中英

Java/Kotlin - 将 Set 转换为 Map <long, set<long> &gt;</long,>

[英]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 吗? (没有forwhile循环的解决方案)

您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM