[英]How to convert a List(List[String]) into a Map[String, Int]?
我有一個List(List("aba, 4"), List("baa, 2"))
,我想將它轉換成 map:
val map : Map[String, Int] = Map("aba" -> 4, "baa" -> 2)
存檔的最佳方式是什么?
更新:
我執行數據庫查詢以檢索數據:val (_, myData) = DB.runQuery(...)
這會返回一對,但我只對第二部分感興趣,它給了我:
myData: List[List[String]] = List(List(Hello, 19), List(World, 14), List(Foo, 13), List(Bar, 13), List(Bar, 12), List(Baz, 12), List(Baz, 11), ...)
scala> val pat = """\((.*),\s*(.*)\)""".r
pat: scala.util.matching.Regex = \((.*),\s*(.*)\)
scala> list.flatten.map{case pat(k, v) => k -> v.toInt }.toMap
res1: scala.collection.immutable.Map[String,Int] = Map(aba -> 4, baa -> 2)
又一次拍攝:
List(List("aba, 4"), List("baa, 2")).
flatten.par.collect(
_.split(",").toList match {
case k :: v :: Nil => (k, v.trim.toInt)
}).toMap
與其他答案的區別:
.par
並行化對的創建,這使我們能夠從多個內核中獲益。PartialFunction
的collect
來忽略不是“key, value”形式的字符串編輯: .par
不會破壞訂單作為答案 state 之前。 只是不能保證列表處理的執行順序,所以函數應該是無副作用的(或者副作用不應該關心順序)。
我的看法:
List(List("aba, 4"), List("baa, 2")) map {_.head} map {itemList => itemList split ",\\s*"} map {itemArr => (itemArr(0), itemArr(1).toInt)} toMap
步驟:
List(List("aba, 4"), List("baa, 2")).
map(_.head). //List("aba, 4", "baa, 2")
map(itemList => itemList split ",\\s*"). //List(Array("aba", "4"), Array("baa", "2"))
map(itemArr => (itemArr(0), itemArr(1).toInt)). //List(("aba", 4), ("baa", 2))
toMap //Map("aba" -> 4, "baa" -> 2)
您的輸入數據結構有點笨拙,所以我認為您無法進一步優化/縮短它。
List(List("aba, 4"), List("baa, 2")).
flatten. //get rid of those weird inner Lists
map {s=>
//split into key and value
//Array extractor guarantees we get exactly 2 matches
val Array(k,v) = s.split(",");
//make a tuple out of the splits
(k, v.trim.toInt)}.
toMap // turns an collection of tuples into a map
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.