如何通过元素的属性将一个集合转换/转换为另一个集合? [英] How to convert/transform a collection to another collection by element's property?

查看:567
本文介绍了如何通过元素的属性将一个集合转换/转换为另一个集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在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:

[的人名。]

我更喜欢使用集合函数而不是:

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

如果,您想要一个不变的列表,它可以简化如下:

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

,使用函数引用表达式代替:

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

这篇关于如何通过元素的属性将一个集合转换/转换为另一个集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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