groupBy

주어진 조건식의 형태로 그룹핑 시킨다

public inline fun <T, K> Iterable<T>.groupBy(keySelector: (T) -> K): Map<K,List<T>> {
    return groupByTo(LinkedHashMap<K, MutableList<T>>(), keySelector)
}

public inline fun <T, K, M : MutableMap<in K, MutableList<T>>>
Iterable<T>.groupByTo(destination: M, keySelector: (T) -> K): M {
    for (element in this) {
        val key = keySelector(element)
        val list = destination.getOrPut(key) { ArrayList<T>() } list.add(element)
    }
    return destination
}



val list = listOf(1, 2, 3, 4, 5)
println(list.groupBy{ if (it % 2 == 0) "even" else "odd" })
// {odd=[1, 3, 5], even=[2, 4]}

Last updated