Hi all, I was wondering if there's something like ...
# getting-started
b
Hi all, I was wondering if there's something like
myMap.mapWithIndex { (index, key, value ) -> .... }
available? I know it's possible with arrays, but I "need" to have an index counter (my current approach is just to have a counter var, but I was hoping there would be something more elegant)
d
hi, i don't think it's wise to deal with index together when using map. Map is designed to be accessed via key and value, so there is no way or even guarantee of insertion order in map. You could probably do another way which is to create a sortedMap(), but that still does not give you the index way of enumerating the map.
b
Appreciate the feedback, but having or not having an index is not really an option here: in my map, I'm creating
Column
objects which require a key, a value, and an index. The insertion order etc isn't really important for me, I'm not using the index, it's just a required parameter for the creation of Columns
d
Ok, so that is what you mean by index. Could this be something you are looking for?
Copy code
data class Column(var index: Int, var key: String, var value: String)

var myMap = mapOf("a" to "aa", "b" to "bb", "c" to "cc")
var myList = myMap.toList().mapIndexed { index, pair -> Column(index, pair.first, pair.second) }

println(myList)
i
You can iterate/map with index
map.entries
collection:
Copy code
map.entries.mapIndexed { index, (key, value) -> Column(index, key, value) }
👍 4
b
Both, thank you! I’ll go for Ilya’s solution, it’s a bit more elegant!
👍 1