Scala Map减少和聚合

时间:2016-06-29 16:11:10

标签: scala

我有一个看起来像这样的Map,它是Type Map [String,Seq [String]]

Map(
 "5" -> Seq("5.1"),
 "5.1" -> Seq("5.1.1", "5.1.2"),
 "5.1.1" -> Seq("5.1.1.1"),
 "5.1.2" -> Seq.empty[String],
 "5.1.1.1" -> Seq.empty[String]
)

给定一个键,我想以递归方式获取属于给定键的所有值。比如说。如果我想查找键5,我希望结果是:

Given Input is: 5
Expected Output is: Seq(5.1, 5.1.1, 5.1.2, 5.1.1.1)

这是我到目前为止所尝试的内容:

def fetchSequence(inputId: String, acc: Seq[String], seqMap: Map[String, Seq[String]]): Seq[String] = seqMap.get(inputId) match {
  case None => acc
  case Some(subSeq) =>
    val newAcc = acc ++ subSeq
    subSeq.collect {
      case subId=> fetchSequence(subId, newAcc, seqMap)
    }.flatten
}

当我使用上面的Map调用fetchSequence时,我得到一个空结果。

1 个答案:

答案 0 :(得分:4)

更简洁:

def recGet[A](map: Map[A, Seq[A]])(key: A): Seq[A] = 
  map.get(key).fold(
    // return empty Seq if key not found
    Seq.empty[A])(
    // return a Seq with 
    //   the key and 
    //   the result of recGet called recursively 
    //      (for all the elements in the Seq[A] found for key)
    x => Seq(key) ++ x.flatMap(recGet(map)))

您可以将recGet用作:

val sections = Map(
  "5" -> Seq("5.1"),
  "5.1" -> Seq("5.1.1", "5.1.2"),
  "5.1.1" -> Seq("5.1.1.1"),
  "5.1.2" -> Seq.empty[String],
  "5.1.1.1" -> Seq.empty[String]
)

recGet(sections)("5")      // Seq[String] = List(5, 5.1, 5.1.1, 5.1.1.1, 5.1.2)
recGet(sections)("5.1.1")  // Seq[String] = List(5.1.1, 5.1.1.1)
recGet(sections)("5.2")    // Seq[String] = List()

这也会给你(第一个)元素本身(如果它存在于地图中),如果你不想这样,你可以将recGet包装在另一个使用drop(1)的方法中关于recGet的结果。