How to create a list with an attribute taken from objects of a list in kotlin

Viewed 2700

Let's assume there is a class Person with attributes name and age and there is a list persons with n person objects. Is there a more efficient way of creating an age list from the list persons other than this:

val age_list= ArrayList<Int>()
for(person in persons){
    age_list.add(person.getAge())
}
1 Answers

You can simply map one list to another.

val ageList = persons.map { it.age }

You could also replace the explicit lambda with a function reference.

val ageList = persons.map(Person::age)

If you need to have an ArrayList<Int> as result, you can use the mapTo function to map into an ArrayList<Int> instead of the default List<Int>.

val ageList = persons.mapTo(arrayListOf()) { it.age }

This assumes you have a dataset along the lines of:

data class Person(val name: String, val age: Int)

val persons = listOf(
    Person("Pete", 31),
    Person("Luna", 19),
    Person("Hendrick", 45),
)
Related