https://kotlinlang.org logo
Title
o

Ofir Bar

02/18/2020, 7:28 PM
Is there a method that runs on a collection of objects, returning a collection that contains a specific field from the original collection? ( I tried searching through all collection methods with no success, no google help too) For example:
data class Dog(val id: Int, val name: String)

val dogs = arrayListOf(Dog(0, "jack"), Dog(1,"Jacky"), Dog(2, "Chan"))
val listOfDogsId = dogs.somecoolmethodhere(it.id) // listOfDogsId = arrayListOf<Int>(0,1,2)
b

Brian

02/18/2020, 7:30 PM
j

Javier Troconis

02/18/2020, 7:30 PM
You might want to perform a map over the original collection.Selecting the id
o

Ofir Bar

02/18/2020, 7:36 PM
Exactly!! Thank you my friends @Brian @Javier Troconis (for anyone needing this, this code solved my issue):
val listOfDogsId = dogs.map{it.id}
👍 2
t

tseisel

02/18/2020, 8:19 PM
@Ofir Bar The correct syntax is
val listOfDogIds = dogs.map { it.id }
Or
val listOfDogIds = dogs.map(Dog::id)
if you prefer function references
🍻 1
o

Ofir Bar

02/19/2020, 8:15 AM
Thanks, I fixed my example @tseisel