How do I convert / convert a collection to another collection by an element property?
If I have a collection of an object in Kotlin, is there a quick way to get a collection of a specific property of those objects? I went through the list of collection operations for Kotlin but nothing stood out for me (but I may have missed something)
In python this would be akin to:
[person.name for person in persons]
And I would rather use the collections function rather than do:
var nameMap = mutableListOf<String>()
persons.forEach{person -> nameMap.add(person.name)}
I am sorely lacking in knowledge about filtering / lambda functions and anything other than comprehending lists, so apologies if this is a simple question
source to share
it's easy to do in Kotlin:
// v--- the variable type can be removed
var nameMap: MutableList<String> = persons.map { it.name }.toMutableList();
IF needs immutable List
, it can simplify like below:
// v--- the variable type can be removed
var nameMap: List<String> = persons.map { it.name };
OR , using a function reference expression :
var nameMap = persons.map(Person::name);
source to share