遍历地图以获取密钥的val或val的密钥

时间:2017-11-29 05:28:48

标签: scala

我在下面有一张地图,但如果我们通过" 100"我需要一个能够返回包含以下数字的列表的功能。这是我们通过arg传递的密钥

List(100, 102 , 106 , 107 , 111 , 112) <- example output

基本上,如果key(传入)具有值并且该值具有键

,则添加到列表中
So given we pass in key of 100,
we add 100 to the list and the value is 102, so add that to the list
Then 102 is the new key, so add that to the list
for 102 the value is 107, so add 107 as well to the list...
and so on...



def returnList(key : String): List[String] = {
  Database
  List.empty
}

2 个答案:

答案 0 :(得分:2)

您需要iterate,直到用完关键值。

Iterator.iterate("100")(Database.getOrElse(_,"")).takeWhile(_.nonEmpty).toList

这假定空字符串""Map中未找到的值的良好指示符。如果没有良好的指标值,您可以随时使用Option包装器。更加冗长但确切地说Option有什么好处。

Iterator.iterate(Option("100"))(opt => Database.get(opt.head))
        .takeWhile(_.nonEmpty) //stop at first None
        .flatten               //remove Option wrappers
        .toList                //List[String] = List(100, 102, 107, 112)

答案 1 :(得分:1)

val Database = Map(
  "100" -> "102",
  "101" -> "106",
  "102" -> "107",
  "103" -> "108",
  "104" -> "109",
  "105" -> "110",
  "106" -> "111",
  "107" -> "112",
  "108" -> "113",
  "109" -> "114",
  "110" -> "115"
)

def getStrangeListForKey(database: Map[String, String], key: String): List[String] = {
  def _getStrangeSetForKey(database: Map[String, String], key: String, acc: Set[String]): Set[String] = {
    database.get(key) match {
      case Some(value) => _getStrangeSetForKey(database, value, acc + value)
      case None => acc
    }
  }

  _getStrangeSetForKey(database, key, Set(key)).toList
}

getStrangeListForKey(Database, "100")