How to convert List to Map in Kotlin?

Technology CommunityCategory: KotlinHow to convert List to Map in Kotlin?
VietMX Staff asked 3 years ago

You have two choices:

  • The first and most performant is to use associateBy function that takes two lambdas for generating the key and value, and inlines the creation of the map:
val map = friends.associateBy({it.facebookId}, {it.points})
  • The second, less performant, is to use the standard map function to create a list of Pair which can be used by toMap to generate the final map:
val map = friends.map { it.facebookId to it.points }.toMap()