将android hashmap转换为kotlin

时间:2017-06-26 22:31:15

标签: java android 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中。

4 个答案:

答案 0 :(得分:5)

您可以直接实例化HashMap。您可以使用forEachIndexed代替for循环(如果objectsArrayIterable)。

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

在您的代码版本中,您获得null,因为您将其分配给myMap。此外,您可能只有一个值,因为您只设置了"sample"密钥进行测试。

答案 1 :(得分:3)

晚会,但你也可以使用

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

答案 2 :(得分:2)

如果你想在循环中改变地图,你需要使用val myMap = mutableMapOf<String, Int>()

答案 3 :(得分:0)

您应该初始化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)