Introduce toMap with key-value pair selector.

#KT-6657
This commit is contained in:
Ilya Gorbunov
2015-11-30 04:19:52 +03:00
parent 2966420d24
commit 544bc9a70c
6 changed files with 232 additions and 3 deletions
@@ -1082,6 +1082,20 @@ public inline fun <T, K, V> Iterable<T>.toMap(selector: (T) -> K, transform: (T)
return result
}
/**
* Returns a [Map] containing key-value pairs provided by [transform] function applied to elements of the given collection.
* If any of two pairs would have the same key the last one gets added to the map.
*/
@kotlin.jvm.JvmName("toMapOfPairs")
public inline fun <T, K, V> Iterable<T>.toMap(transform: (T) -> Pair<K, V>): Map<K, V> {
val capacity = (collectionSizeOrDefault(10)/.75f) + 1
val result = LinkedHashMap<K, V>(Math.max(capacity.toInt(), 16))
for (element in this) {
result += transform(element)
}
return result
}
/**
* Returns a [Map] containing the elements from the given collection indexed by the key
* returned from [selector] function applied to each element.