I have a class Person:

class Person(var fullName: String, var nickname: String, var age: Int)

In my code, at some point I have a List of Person objects, and a list of nicknames.

var people: List<Person> = listOf(
  Person("Adam Asshat", "dontinviteme", 21),
  Person("Bob Bowyer", "bob", 37),
  Person("Emily Eden", "emily", 22)
)

var invitedToParty: List<String> = listOf("bob", "emily")

Now I want to get a List with only Bob and Emily by using lambda's, but I'm not sure how I'd go about it in Kotlin.

var invitedPeople: List<Person> = // a lambda that results in a list containing only Bob and Emily's objects

In C# I'd probably use LINQ and a .where()-method combined with an == any() but Kotlin doesn't seem to have anything like that from what I've found.

Is this even possible in Kotlin lambda's?

推荐答案

在C#中,您将执行以下操作:

people.Where(p => invitedToParty.Any(s => s == p.nickname));

Likewise in Kotlin, you'd use filter which is like Where and any speaks for it self:

people.filter { p -> invitedToParty.any { it == p.nickname } }

或使用contains:

people.filter { invitedToParty.contains(it.nickname) }

Kotlin相关问答推荐

为何Kotlin标准库中的AND和OR函数不能像&&和||一样进行短路运算?

找不到有效的 Docker 环境

mutableStateOf 和 mutableStateListOf 有什么区别?

为什么 trySend 会发出假数据?

jlink:在合并模块和 kotlin.stdlib 中打包 kotlin.*

Kotlin 中的密封和内部有什么区别?

如何将glide显示的图像下载到设备存储中.Kotlin

伴随对象在变量更改时更改它的值

Moshi:解析单个对象或对象列表(kotlin)

类型是什么意

包括登录Elvis operator?

Kotlin:如何在活页夹中返回正在运行的服务实例?

Android Studio 4.0.0 Java 8 库在 D8 和 R8 构建错误中脱糖

kotlin RecyclerView分页

Android 与 Kotlin - 如何使用 HttpUrlConnection

Kotlin/JS,Gradle 插件:无法加载@webpack-cli/serve命令

在kotlin中初始化类变量的正确位置是什么

lateinit 的 isInitialized 属性在伴随对象中不起作用

在 IntelliJ Idea 中未为 Kotlin @ConfigurationProperties 类生成 spring-configuration-metadata.json 文件

如何在 firebase 数据库中使用 kotlin 协程