Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to convert a string into a HashMap

Tags:

parsing

kotlin

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?

like image 376
ycomp Avatar asked Dec 18 '16 14:12

ycomp


People also ask

How do I convert a String to a HashMap key?

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.

Can we convert String to HashMap in java?

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.

Can we use StringBuilder as key in HashMap?

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.

Why String is a good key for HashMap?

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.


2 Answers

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.

like image 112
hotkey Avatar answered Oct 08 '22 20:10

hotkey


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()
like image 23
dux2 Avatar answered Oct 08 '22 22:10

dux2