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

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

问题描述

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

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函数,该函数需要两个lambda来生成键和值,并内联地图的创建:

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中将List转换为Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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