J. Doe
J. Doe

Reputation: 105

String of Key-Value Pairs to Map

I have strings of the following pattern. "\key1\value1\key2\value2\..."

How can these be turned into a Map("key1" -> "value1", "key2" -> "value2") elegantly?

Upvotes: 3

Views: 1168

Answers (1)

dth
dth

Reputation: 2337

Your example is an invalid string literal as \ is the escape character, so I assume you wanted a -character before each value and key, even before the first one.

If that's the case you can do what you want like this:

val s = """\key1\value1\key2\value2"""
s.split('\\').toList.tail.grouped(2).map{case List(a,b) => a -> b}.toMap

Consult the API documentation on List to find what the Operations are doing.

Upvotes: 7

Related Questions