如果我在Kotlin中有一个对象的集合,有没有快速的方法来获取这些对象的某个属性的集合?我看了一张collection operations for Kotlin人的名单,但没有什么特别适合我(但我可能忽略了一些东西)

In python it would be akin to:

[person.name for person in persons]

而且我更喜欢使用集合函数,而不是执行以下操作:

var nameMap = mutableListOf<String>()
persons.forEach{person -> nameMap.add(person.name)}

I'm pretty lacking in knowledge of filtering/lambda functions and anything other than list comprehension, so apologies if this is a simple question

推荐答案

it's easy to do in Kotlin:

//           v--- the variable type can be removed
var nameMap: MutableList<String> = persons.map { it.name }.toMutableList();

IF你想要一个不变的List,它可以简化如下:

//           v--- the variable type can be removed
var nameMap: List<String> = persons.map { it.name };

OR using function reference expression instead:

var nameMap = persons.map(Person::name);

Kotlin相关问答推荐

Fleet无法从构建文件自动重新加载更改错误'

在Kotlin中将ClosedRange字符串转换为List?<>

为什么onEach不是挂起函数,而Collect是?

如何使用 Kotlin Maven 更改 Minecraft 插件中的 Shulker GUI 标题

Rabin-Karp字符串匹配的实现(Rolling hash)

使用 Jetpack Compose 使用参数导航

使用 StateFlow 时如何移除监听器?

通过顺序多米诺骨牌操作列表管理对象的最佳方法是什么?

我们应该在 Effect 和 Either 之间 Select 哪个作为我们业务服务的返回类型?

kotlin 单例异常是好是坏?

is return inside function definition 也是 kotlin 中的表达式

OnClickListener 未在 ConstraintLayout 上触发

JobIntentService 被销毁,当应用程序被销毁时

调用单元测试验证伴随对象方法

将 @Component.Builder 与构造函数参数一起使用

Kotlin解构when/if语句

Tornadofx - 如何在每个实例上将参数传递给 Fragment

具有泛型param的Kotlin抽象类和使用类型param的方法

旋转 kotlin 数组

Android Kotlin .visibility