1
votes

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.

2
What do you by a vector? Should line 2 be List("", "", "value3", "value4", "value5") or List("value3", "value4", "value5")? Could you provide as well what you've already tried?Xavier Guihot
Please post what the resulting Vector should look like (i.e. its contents) along with whatever code you've tried so far.jwvh
This is how I dealt with the situation val readFile = scala.io.Source.fromFile(Path+"/test.txt").getLines.map(line => { val tokens = line.split("""\=+""") // Use a regex to avoid empty tokens. Splitting file to 2 column and then a list (tokens(0), tokens(1)) }).toList val matchKey = readMapingFile.filter(_._1==Keys.trim()) val pickMatchedKV = matchKey(0) // I don't have duplicate keys in my case val value = pickMatchedKV._2 val spiltValuestoArray = value.split("~") spiltValuestoArray.foreach(println) passed keys via KeysSat

2 Answers

1
votes

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.

1
votes

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))