如何在 Kotlin 中将列表转换为地图? [英] How to convert List to Map in Kotlin?

查看:39
本文介绍了如何在 Kotlin 中将列表转换为地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有一个字符串列表,如:

For example I have a list of strings like:

val list = listOf("a", "b", "c", "d")

我想将其转换为地图,其中字符串是键.

and I want to convert it to a map, where the strings are the keys.

我知道我应该使用 .toMap() 函数,但我不知道如何使用,而且我还没有看到任何示例.

I know I should use the .toMap() function, but I don't know how, and I haven't seen any examples of it.

推荐答案

您有两个选择:

第一个也是最高效的是使用 associateBy 函数,它接受两个 lambdas 来生成键和值,并内联地图的创建:

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})

第二种,性能较差,是使用标准的map 函数创建一个Pair 列表,toMap 可以使用它来生成最终地图:

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()

这篇关于如何在 Kotlin 中将列表转换为地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆