[Kotlin] associateBy, groupBy
collections API ์ค ํ๋๋ก ์ปฌ๋ ์ ์ Map ํํ๋ก ๋ณํ์์ผ์ฃผ๋ API ์ด๋ค.
associateBy ํจ์์ groupBy ํจ์๋ ์ง์ ๋ key์ ์ํด ์ธ๋ฑ์ฑ๋ ์ปฌ๋ ์ ์ ์์๋ก๋ถํฐ Map์ ๋ง๋ค์ด์ค๋ค.
associateBy
public inline fun <T, K> Iterable<T>.associateBy(keySelector: (T) -> K): Map<K, T> {
val capacity = mapCapacity(collectionSizeOrDefault(10)).coerceAtLeast(16)
return associateByTo(LinkedHashMap<K, T>(capacity), keySelector)
}
๋งค๊ฐ๋ณ์์๋ T๋ฅผ ์ ๋ฌํ๊ณ key๋ฅผ ๋ฆฌํดํ๋ ๋๋คํจ์ keySelector๋ฅผ ์ธ์๋ก ๋ฐ๋๋ค.
๋งค๊ฐ๋ณ์๋ก ๋ฐ์ keySelector๋ฅผ key๋ก, List์ ์ธ์๋ฅผ value๋ก Map<K,V>๋ฅผ ๋ง๋ค์ด ๋ฆฌํดํ๋ค.
์์
fun main() {
val statuses = listOf(Status("Running"), Status("Pending"), Status("Failed"))
private val mapping = statuses.associateBy(Phase::value)
// ๊ฒฐ๊ณผ : {Running=Status("Running"), Pending=Status("Pending"), Failed=Status("Failed")}
}
groupBy
public inline fun <T, K> Array<out T>.groupBy(keySelector: (T) -> K): Map<K, List<T>> {
return groupByTo(LinkedHashMap<K, MutableList<T>>(), keySelector)
}
List๋ฅผ Map ํํ๋ก ๋ณํ์์ผ์ฃผ๋ ํจ์์ด๋ค.
associateBy์ ๋ฌ๋ฆฌ, key๊ฐ ์ค๋ณต๋์ด๋ value๋ฅผ ๋ฆฌ์คํธ๋ก ๋ง๋ค์ด ์ฃผ๊ธฐ ๋๋ฌธ์ ๊ฐ ์ ์ค์ด ์๋ค. (associateBy๋ key ์ค๋ณต์, ๋ง์ง๋ง์ ์๋ ์์๊ฐ value๊ฐ ๋๋ค.)
์์
fun main() {
val statuses = listOf(Status("Running"), Status("Pending"), Status("Failed"))
private val mapping = statuses.groupBy(Phase::value)
// ๊ฒฐ๊ณผ : {Running=[Status("Running")], Pending=[Status("Pending")], Failed=[Status("Failed")]}
}
value๊ฐ list๋ก ๋ฌถ์ฌ์๋ ๊ฒ์ ๋ณผ ์ ์๋ค.
๋งค๊ฐ๋ณ์๋ก 2๊ฐ๋ฅผ ๋ฃ๋๋ค๋ฉด ๊ฐ๊ฐ์ key์ value์ด๋ค.