Scala-map和Flatten显示与Flat Map不同的结果

cwdobuhd  于 2022-11-09  发布在  Scala
关注(0)|答案(1)|浏览(148)
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))

我不确定这里发生了什么。我期待着他们两个人都能得到同样的结果。

wqsoz72f

wqsoz72f1#

.flatMapMap.flatMap,但.mapIterable.map
对于Map"Logging" -> "Networking""Logging" -> "Game"只是变成后者的"Logging" -> "Game",因为密钥是相同的。

val adjList: Map[String, List[String]] = Map("Logging" -> List("Networking", "Game"))
val x0: Map[String, String] = adjList.flatMap { case (v, vs) => vs.map(n => (v, n)) } 
//Map(Logging -> Game)
val x: List[(String, String)] = x0.toList 
//List((Logging,Game))
val adjList: Map[String, List[String]] = Map("Logging" -> List("Networking", "Game"))
val y0: immutable.Iterable[List[(String, String)]] = adjList.map { case (v, vs) => vs.map(n => (v, n)) } 
//List(List((Logging,Networking), (Logging,Game)))
val y1: immutable.Iterable[(String, String)] = y0.flatten
//List((Logging,Networking), (Logging,Game))
val y: List[(String, String)] = y1.toList
//List((Logging,Networking), (Logging,Game))

也是https://users.scala-lang.org/t/map-flatten-flatmap/4180

相关问题