Joel Broström
Joel Broström

Reputation: 4080

How to return member values in a array of objects using lambda expressions

I have an array of "Dog" where i want to print the name of all dogs older then 5 years.

I tried something like

Dogs.filter{ it.age > 5 }.forEach { it.name }

This gives me the value i need, but how do I store and return it as a list of strings? I tried things like adding .join(",") but since I don't get any array in return it wont work.

Upvotes: 3

Views: 1084

Answers (1)

zsmb13
zsmb13

Reputation: 89608

I think you're looking for the map operator:

val dogNames: List<String> = dogs.filter { it.age > 5 }.map { it.name }

Upvotes: 10

Related Questions