if I have some text in a String like:
"abc=123,def=456,ghi=789"
how could I create a populated HashMap<String,Int>
object for it in the easiest, shortest amount of code possible in Kotlin?
String is as a key of the HashMap When you create a HashMap object and try to store a key-value pair in it, while storing, a hash code of the given key is calculated and its value is placed at the position represented by the resultant hash code of the key.
We can also convert an array of String to a HashMap. Suppose we have a string array of the student name and an array of roll numbers, and we want to convert it to HashMap so the roll number becomes the key of the HashMap and the name becomes the value of the HashMap. Note: Both the arrays should be the same size.
You should use the String for a key. StringBuilder/Buffer is also mutable which is generally not a good idea to use as a key for a HashMap since storing the value under it can cause the value to be inaccessible after modification.
Immutability is a great mechanism to get same hash code every time, for a key object. Hence always it is ideal to go for String and it solves memory leaks, value unavailability, etc., hashCode() and equals() methods contract is playing around when data is stored in HashMap.
I can think of no solution easier than this:
val s = "abc=123,def=456,ghi=789"
val map = s.split(",").associate {
val (left, right) = it.split("=")
left to right.toInt()
}
Or, if you need exactly a HashMap
, use .associateTo(HashMap()) { ... }
.
Some details:
.associate { ... }
receives a function that produces pairs which are then stored into a map as keys and values respectively.
val (left, right) = it.split("=")
is the usage of destructuring declarations on the list returned from it.split("=")
, it takes the first two items from the list.
left to right.toInt()
creates a Pair<String, Int>
defining a single mapping.
You can map each key/value to a Pair
with the to
keyword. An iterable of Pair
can be mapped to a Map easily with the toMap()
extension method.
val s = "abc=123,def=456,ghi=789"
val output = s.split(",")
.map { it.split("=") }
.map { it.first() to it.last().toInt() }
.toMap()
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