2017-11-16 7 views
0

に入れなければならないしている私は、フォームのリストを持っています1つの文字列でこれを行う方法についてオンラインで解決策を見つけましたが、それを文字列のリストに適合させることはできませんでした。スカラ文字列のリストは、カンマで分割され、地図

また、マッピングする前に数値をInt/Doubleにキャストする必要があります。

私は助けていただきありがとうございます。

答えて

2

これはfold

// Your input 
val lines = List("a,1", "b,2", "gretzky,99", "tyler,11") 

// Fold over the lines, and insert them into a map 
val map = lines.foldLeft(Map.empty[String, Int]) { 
    case (map, line) => 

    // Split the line on the comma and separate the two parts 
    val Array(string, num) = line.split(",") 

    // Add new entry to the map 
    map + (string -> num.toInt) 
} 

println(map) 

出力のための完璧な仕事です:

Map(a -> 1, b -> 2, gretzky -> 99, tyler -> 11) 
1
おそらく

ないことを行うための最善の方法、それはあなたのニーズを満たす必要があり

yourlist.groupBy(_.split(',')(0)).mapValues(v=>v(0).split(',')(1)) 
関連する問題