https://kotlinlang.org logo
Title
b

bodiam

03/01/2020, 2:23 AM
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

deactivateduser

03/01/2020, 2:35 AM
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

bodiam

03/01/2020, 2:55 AM
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

deactivateduser

03/01/2020, 3:05 AM
Ok, so that is what you mean by index. Could this be something you are looking for?
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

ilya.gorbunov

03/01/2020, 3:55 AM
You can iterate/map with index
map.entries
collection:
map.entries.mapIndexed { index, (key, value) -> Column(index, key, value) }
👍 4
b

bodiam

03/01/2020, 4:51 AM
Both, thank you! I’ll go for Ilya’s solution, it’s a bit more elegant!
👍 1