Search code examples
javasequencejava-streamkotlincollect

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


Suppose I have a list of persons and would like to have Map<String, Person>, where String is person name. How should I do that in kotlin?


Solution

  • Assuming that you have

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

    the associateBy function would probably satisfy you:

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

    As said in 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.

    It's applicable to any Iterable.