Home > Mobile >  Java/Kotlin - convert Set to Map<Long, Set<Long>>
Java/Kotlin - convert Set to Map<Long, Set<Long>>

Time:11-29

I have Set of Long values

Set<Long> ids = {1,2,3,4}

What I'd like to achieve is

Set<Map<Long, Set<Long>>

and from this Set of ids I need to have Set with 4 elements like:

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
}

How can i get it by stream or maybe kotlin's groupBy ?

Was anyone going to have a map like this? (Solution without a for or while loop)

CodePudding user response:

You can use use map method to transform every element to Map then collect it to set

var set = setOf(1, 2, 3, 4)
var map = set.map { v -> mapOf(v to set.filter { it != v }.toSet()) }
    .toSet()

However I don't believe it's much better than simple foreach loop due to performance or readability

CodePudding user response:

Opinions on kotlin groupBy

Notice that groupBy can just split the original set into severial sets without intersection. So it's impossible to construct the mentioned map directly with groupBy function.

The solution below take advantage of groupBy when getting result, but result2 is much more clear to read and meets intuition:

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]}
}

CodePudding user response:

That would be a possible solution with a for loop:

val ids: Set<Long> = setOf(1, 2, 3, 4)

var result: MutableSet<Map<Long, Set<Long>>> = mutableSetOf()

for (id in ids) {
  result.add(mapOf(id to ids.filter { it != id }.toSet()))
}

println(result)
  • Related