Associate operation is used to create a map from list of objects. There are three ways in which association can be performed on any List<A>
:
associateWith | associateBy | associate | |
---|---|---|---|
Abbreviation | A → V | K → A | K → V |
Key | Type - A, from List | Custom, from keySelector lambda | Custom, from keySelector lambda |
Value | Custom, from valueSelector lambda | Type - A, from List | Custom, from valueSelector lambda |
Implementation of all three operations is similar, difference lies in the way pair for the map is formed. We can use the map()
function to map the elements in the list to the required pairs for the map. Then List<Pair>
can be converted to map using toMap()
function.
fun <A, K, V> List<A>.associate(
pairSelector: (A) -> Pair<K, V>
): Map<K, V> {
return map { pairSelector(it) }.toMap()
}
fun <A, K> List<A>.associateBy(
keySelector: (A) -> K
): Map<K, A> {
return map { keySelector(it) to it }.toMap()
}
fun <A, V> List<A>.associateWith(
valueSelector: (A) -> V
): Map<A, V> {
return map { it to valueSelector(it) }.toMap()
}