如何通过元素的属性将集合转换/转换为另一个集合? [英] How to convert/transform a collection to another collection by element's property?
问题描述
如果我在 Kotlin 中有一个对象的集合,是否有一种快速的方法来获取这些对象的某个属性的集合?我查看了 Kotlin 的集合操作 的列表,但对我来说没有什么特别突出的(但我可能忽略了一些东西)
If I have a collection of an object in Kotlin, is there a quick way to get a collection of a certain property of those objects? I looked at a list of collection operations for Kotlin, but nothing stood out for me (but I may have overlooked something)
在python中它类似于:
In python it would be akin to:
[person.name for person inperson]
而且我更喜欢使用集合函数而不是这样做:
And I'd prefer to use a collections function instead of doing:
var nameMap = mutableListOf<String>()
persons.forEach{person -> nameMap.add(person.name)}
我对过滤/lambda 函数以及列表理解以外的任何知识都非常缺乏,所以如果这是一个简单的问题,我深表歉意
I'm pretty lacking in knowledge of filtering/lambda functions and anything other than list comprehension, so apologies if this is a simple question
推荐答案
在 Kotlin 中很容易做到:
it's easy to do in Kotlin:
// v--- the variable type can be removed
var nameMap: MutableList<String> = persons.map { it.name }.toMutableList();
如果你想要一个不可变的List
,它可以简化如下:
IF you want an immutable List
, it can simplify as below:
// v--- the variable type can be removed
var nameMap: List<String> = persons.map { it.name };
OR 使用函数引用表达式相反:
var nameMap = persons.map(Person::name);
这篇关于如何通过元素的属性将集合转换/转换为另一个集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!