I am creating a Map from a List as follows:
List strings = Arrays.asList(\"a\", \"bb\", \"ccc\");
Map
In Kotlin, toMap() is order-preserving.
funIterable >.toMap(): Map Returns a new map containing all key-value pairs from the given collection of pairs.
The returned map preserves the entry iteration order of the original collection. If any of two pairs would have the same key the last one gets added to the map.
Here's its implementation:
public fun Iterable>.toMap(): Map {
if (this is Collection) {
return when (size) {
0 -> emptyMap()
1 -> mapOf(if (this is List) this[0] else iterator().next())
else -> toMap(LinkedHashMap(mapCapacity(size)))
}
}
return toMap(LinkedHashMap()).optimizeReadOnlyMap()
}
The usage is simply:
val strings = listOf("a", "bb", "ccc")
val map = strings.map { it to it.length }.toMap()
The underlying collection for map is a LinkedHashMap (which is insertion-ordered).