Reputation: 73
New to scala. I have a key value file containing
key1=value1~value2
key2=value3~value4~value5
key3=value7~value8
I want to load it to a map from a file. I want to find and match if I receive key1 or key2 at run time. Then store the corresponding values (separated by ~) to a vector. So that I can do foreach on the vector and perform different things based on the value.
Upvotes: 1
Views: 1416
Reputation: 709
Let's assume you have file test.txt
which contains:
key1=value1~value2
key2=value3~value4~value5
key3=value7~value8
Below code will parse and create List of Tuple
with key and related to it List
(it could be easily convert to Map
-> just invoke toMap
):
val filename = "test.txt"
val result = Source.fromFile(filename).getLines
.map(line => {
line.split("=") match {
case Array(a, b) => (a, b.split("~").toList)
}
}).toList
println(result)
The result would be:
List((key1,List(value1, value2)), (key2,List(value3, value4, value5)), (key3,List(value7, value8)))
If you want Map
you need just invoke toMap
:
println(result.toMap)
Result for that would be:
Map(key1 -> List(value1, value2), key2 -> List(value3, value4, value5), key3 -> List(value7, value8))
Upvotes: 1
Reputation: 473
Here is the solution, though it might not be the ideal solution, though it will give you the desired output:
Read lines from the file
val list = Source.fromFile("path").getLines().toList
then do the following:
val outPutList = list.map { data =>
val splittedList = data.split("=").toList
val listOfTupple =(splittedList.head,splittedList.tail.mkString.split("~").toList)
listOfTupple
}
outPutList.toMap
Expected Output:
Map(key1 -> List(value1, value2), key2 -> List(value3, value4,value5))
Iterate over the values to perform the desired action.
Upvotes: 1