How do I keep the iteration order of a List when using Collections.toMap() on a stream?

前端 未结 4 2059
自闭症患者
自闭症患者 2020-11-27 15:31

I am creating a Map from a List as follows:

List strings = Arrays.asList(\"a\", \"bb\", \"ccc\");

Map

        
4条回答
  •  误落风尘
    2020-11-27 16:01

    In Kotlin, toMap() is order-preserving.

    fun  Iterable>.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).

提交回复
热议问题