Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert android hashmap to kotlin

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.

like image 250
user2661518 Avatar asked Jun 26 '17 22:06

user2661518


People also ask

Does kotlin have HashMap?

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.

How do I return a HashMap in Kotlin?

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.


3 Answers

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.

like image 186
tynn Avatar answered Oct 11 '22 07:10

tynn


Late to the party, but you can also use

val myMap = objects.withIndex().associateTo(HashMap<String, Int>()) {
    it.value to it.index
}
like image 42
Ruckus T-Boom Avatar answered Oct 11 '22 06:10

Ruckus T-Boom


You need to use val myMap = mutableMapOf<String, Int>() if you want to mutate the map within the loop.

like image 34
JK Ly Avatar answered Oct 11 '22 06:10

JK Ly