将android hashmap转换为kotlin

我有一个Java HashMap填充为

 HashMap<String, Integer> myMMap = new HashMap<String, Integer>(); for (int i = 0; i < objects.size(); ++i) { myMap.put(objects.get(i), i); } 

我试图把它转换成Kotlin。 我尝试了下面的方式,但我得到它的空值。

 var myMap : HashMap<String, Int>? = null for (i in objects){ //myMap?.put(i, objects.indexOf(i)) myMap?.put("sample", 3) System.out.println("myMapInForLoop" + myMap) } 

它打印I/System.out: myMapInForLoopnull

我试过使用hashMapOf函数,但它只允许1个值,所以我不能把它放在我的myMap

你可以直接实例化HashMap 。 例如,如果objectsArrayIterable则可以使用forEachIndexed来代替for循环。

 val myMap = HashMap<String, Int>() objects.forEachIndexed { index, item -> myMap.put(item, index) System.out.println("myMapInForLoop" + myMap) } 

在你的代码版本中你得到null ,因为你把它分配给myMap 。 你也可能只有一个值,因为你只设置一个"sample"键进行测试。

如果你想改变循环内的映射val myMap = mutableMapOf<String, Int>()你需要使用val myMap = mutableMapOf<String, Int>()

晚会,但你也可以使用

 val myMap = objects.withIndex().associateTo(HashMap<String, Int>()) { it.value to it.index } 

你应该初始化你的myMap

 val list = listOf("hello", "world", "kotlin", "sfyc23") val myMap = HashMap<String, Int>() for (i in list.indices) { myMap.put(list[i], i) } println(myMap)