scala 将键的所有映射值添加到队列

scala add all the map values of a key to a queue

我目前正在学习如何实现小广度优先算法。我想将 "you" 的值(邻居)添加到搜索队列中。 “+=”操作不起作用。知道如何解决这个问题吗?

import scala.collection.mutable.Map
import scala.collection.mutable.Queue

// creating a hash table (allowing to set a map of key, value)
val graph = Map("you" -> ("bob", "claire", "alice"), "alice" -> ("peggy"), "bob" -> ("peggy", "anuj"), "claire" -> ("jonny", "thom"))

graph("bob") // prints the neighbors of "bob"
var search_queue = new Queue[]()
search_queue += graph("you")
println(search_queue)

你有几个问题。

首先,您的 graph Map 来自 String key,到 元组 。但是由于你的元组有不同的大小,编译器最终推断 java.io.Serializable - 我会使用 List 或其他集合作为值。

其次,您可以使用 empty constructor 而不是 new 来实例化 search_queue

第三,如果您想将多个值添加到可变集合中,您可以使用 ++= operator,而不是循环每个值并使用 +=.

第四,您只需要集合是可变的,而不是对它的引用 - 因此您可以使用 val.

也许这段代码可以帮到你。

import scala.collection.mutable.Queue

val graph = Map(
  "you" -> List("bob", "claire", "alice"),
  "alice" -> List("peggy"),
  "bob" -> List("peggy", "anuj"),
  "claire" -> List("jonny", "thom")
)

val searchQueue = Queue.empty[String]

searchQueue ++= graph.getOrElse("you", List.empty[String])
// searchQueue = Queue(bob, claire, alice)