Java 8 stream.collect(Collectors.toMap()) 在科特林中模拟

Java 8 stream.collect(Collectors.toMap()) analog in kotlin

假设我有一个人员列表并且想要 Map<String, Person>,其中 String 是人员姓名。我应该如何在科特林中做到这一点?

假设你有

val list: List<Person> = listOf(Person("Ann", 19), Person("John", 23))

associateBy 函数可能会让您满意:

val map = list.associateBy({ it.name }, { it.age })
/* Contains:
 * "Ann" -> 19
 * "John" -> 23
*/

如 KDoc 中所述,associateBy:

Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given array.

If any two elements would have the same key returned by keySelector the last one gets added to the map.

The returned map preserves the entry iteration order of the original array.

它适用于任何Iterable

Kotlin 中的许多替代方案:)

val x: Map<String, Int> = list.associate { it.name to it.age }
val y: Map<String, Int> = list.map { it.name to it.age }.toMap()
var z: Map<String, Int> = list.associateBy({ it.name }, { it.age })

对于这种特殊情况,IMO 的最佳选择是第一个,因为不需要 Lambda,而是简单的转换。