2013-01-04 61 views
0

有嵌套路徑的線像鑰匙:變換地圖路徑 - >值成樹狀圖

Map(
    "manufacturer" -> "Magnavox", 
    "processor.address-space" -> 8, 
    "gpu.processor.address-space" -> 8, 
    "processor.speed" -> 150 
) 

怎麼可能是一個地道的斯卡拉基於路徑分組的值,把它變成:

Map(
    "gpu" -> Map(
      "processor" -> Map("address-space" -> 8) 
      ), 
    "processor" -> Map(
        "speed" -> 150, 
        "address-space" -> 8 
       ), 
    "manufacturer" -> "Magnavox" 
) 

注意:所有鍵路徑,所以,不gpu -> "something"被允許作爲在這種情況下的輸入。

回答

2
def group(m: Map[String, Any]): Map[String, Any] = { 
    def groupImpl(dic: Map[Array[String], Any]): Map[String, Any] = { 
    dic.groupBy(_._1.head).mapValues{ dic: Map[Array[String], Any] => 
     require(!dic.isEmpty) 
     if (dic.size == 1 && dic.head._1.size == 1) { 
     dic.head._2 
     } 
     else { 
     groupImpl(
      dic.map{ case (k,v) => 
      require(!k.tail.isEmpty) 
      k.tail -> v 
      } 
     ) 
     } 
    } 
    } 
    groupImpl(m.map{ case (k,v) => k.split("\\.") -> v}) 
} 

一些測試:

scala> 
group(
    Map(
    "manufacturer" -> "Magnavox", 
    "processor.address-space" -> 8, 
    "gpu.processor.address-space" -> 8, 
    "processor.speed" -> 150, 
    "gpu.processor.foo" -> "bar" 
) 
) 

res2: Map[String,Any] = Map(manufacturer -> Magnavox, processor -> Map(speed -> 150, address-space -> 8), gpu -> Map(processor -> Map(foo -> bar, address-space -> 8)))