Iterate over a collection and create a map

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?

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...

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

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

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

2 Likes

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