Iterate over a collection and create a map


#1

I need something like Python dict comprehensions:

id_to_name = {p.id: p.name for p in persons}

which is equivalent to:

id_to_name = dict((p.id, p.name) for p in persons)

In Kotlin I have to do it this way:

idToName = persons.map { it.id to it.name }.toMap()

where toMap is:

fun <K, V> Iterable<Pair<K, V>>.toMap(): Map<K, V> {   val result = HashMap<K, V>()   for (x in this) {   val (k, v) = x   result.put(k, v)   }   return result }

What's the best way of creating a map in Kotlin for this task? Is there something like toMap in stdlib?


#2

The only "oneliner" I've found is:

persons.fold(HashMap<Int, String>(), { map, person -> map.put(person.id, person.name); map })

Not so pretty as python's version...


#3

Looks like it's a good thing to add to our standard library. A pull request would be welcome :)


#4

Did anything happen on this? i.e. list, set and “dictionary” comprehensions.


#5

No, there is no comprehensions available, but toMap and associateBy extension functions are at your disposal.


#6

Whilst I knew of groupBy I wasn’t aware of associateBy, I shall investigate.