I have a Java HashMap
populated as
HashMap<String, Integer> myMMap = new HashMap<String, Integer>();
for (int i = 0; i < objects.size(); ++i) {
myMap.put(objects.get(i), i);
}
And I'm trying to convert this to Kotlin. I tried the way below, but I'm getting null value in it.
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)
}
It prints I/System.out: myMapInForLoopnull
.
I've tried using hashMapOf
function, but it allows only 1 value, so I cannot put that in myMap
.
In this tutorial, we'll show you many Kotlin HashMap methods and functions that also work on Android. You will see many examples to: Create, initialize, add item, get value, update, remove entries in a HashMap.
Kotlin HashMap Example 4 - containsKey(key) and containsValue(value) The Function containsKey() returns true if the specified key is present in HashMap or returns false if no such key exist. The Function containsValue() is used to check whether the specified value is exist in HashMap or not.
You can instantiate the HashMap
directly. Instead of a for-loop you could then use forEachIndexed
for example (if objects
is an Array
or Iterable
).
val myMap = HashMap<String, Int>()
objects.forEachIndexed { index, item ->
myMap.put(item, index)
System.out.println("myMapInForLoop" + myMap)
}
In your version of the code you get null
, because you assign it to myMap
. Also you might have only a single value, because you only set a "sample"
key for testing.
Late to the party, but you can also use
val myMap = objects.withIndex().associateTo(HashMap<String, Int>()) {
it.value to it.index
}
You need to use val myMap = mutableMapOf<String, Int>()
if you want to mutate the map within the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With