How to return member values in a array of objects

2019-02-20 12:25发布

问题:

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.

回答1:

I think you're looking for the map operator:

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