val adjList = Map("Logging" -> List("Networking", "Game"))
// val adjList: Map[String, List[String]] = Map(Logging -> List(Networking, Game))
adjList.flatMap { case (v, vs) => vs.map(n => (v, n)) }.toList
// val res7: List[(String, String)] = List((Logging,Game))
adjList.map { case (v, vs) => vs.map(n => (v, n)) }.flatten.toList
// val res8: List[(String, String)] = List((Logging,Networking), (Logging,Game))
我不确定这里发生了什么。我期待着他们两个人都能得到同样的结果。
1条答案
按热度按时间wqsoz72f1#
.flatMap
是Map
的.flatMap
,但.map
是Iterable
的.map
。对于
Map
,"Logging" -> "Networking"
和"Logging" -> "Game"
只是变成后者的"Logging" -> "Game"
,因为密钥是相同的。也是https://users.scala-lang.org/t/map-flatten-flatmap/4180