对 Kotlin 的 associateWith 映射转换扩展函数的文档感到困惑

Confused about documentation of Kotlin's associateWith map transformation extension function

尝试研究 Kotlin 中的集合转换,我对 associateWith 转换扩展函数的文档感到有点困惑。

它说:

The basic association function associateWith() creates a Map in which the elements of the original collection are keys, and values are produced from them by the given transformation function. If two elements are equal, only the last one remains in the map.

然而,当我使用包含重复元素(即它们相等)的列表测试此函数时,最后一个被排除在地图之外,只有第一个是那个与文档中所说的相反。

fun main() {
val numbers = listOf("one", "two", "three", "four", "five", "four")
val mapOfNumbers = numbers.associateWith { it.length }
println(mapOfNumbers) //the first "four" element is the one that remains in the map
}

Running this in the Kotlin Playground prints the following

{one=3, two=3, three=5, four=4, five=4}

文档中的措辞是否有误,还是我的思路遗漏了什么?

the last one gets excluded from the map, and only the first is the one that remains

你没有观察到你认为自己在这里的样子。您正在查看地图内容的字符串表示形式。地图通常是无序的,因此查看顺序在这里无济于事。 Kotlin 大多数时候在这种 stdlib 函数中默认创建 LinkedHashMaps,因此它保留了插入顺序。即使第二个 "four" 覆盖了第一个,它仍然会放在那个位置。

文档的意思是,如果存在重复项,并且如果您的转换 lambda 为重复键提供不同的值,则最后一个获胜。此处您的 lambda 为相同的键提供相同的值,因此您无法使用当前代码测试文档的这一部分。

这是一个测试文档内容的示例:

val numbers = listOf("one", "two", "three", "four", "five", "four")

var order = 1
val mapOfNumbers = numbers.associateWith { order++ }
println(mapOfNumbers) // {one=1, two=2, three=3, four=6, five=5}