Kotlin groupby value as set instead of list

You can just use the Kotlin functions groupBy and then mapValues directly on the Set.

You first use groupBy on it.first to get a Map<String, List<Pair<String, Int>>. Then you need to map the values of the resulting map, so you get a List<Int> from the List<Pair<String, Int>>. Like this:

setStringInt.groupBy { it.first }
            .mapValues { entry -> entry.value.map { it.second }.toSet() }

I think this is more readable:

setStringInt.groupBy({ it.first }, { it.second }).mapValues { it.value.toSet() }

using the

inline fun <T, K, V> Iterable<T>.groupBy(
    keySelector: (T) -> K,
    valueTransform: (T) -> V
): Map<K, List<V>>

overload.

Tags:

Kotlin