scala map.span()函数结果无效

时间:2017-06-28 16:23:00

标签: scala

从下面的代码(scala 2.12.2)我希望得到以下结果:

(Map(aa -> 1, ab -> 1, ac -> 1),Map(ba -> 2, bb -> 2, bc -> 2))

但我有以下内容:

(Map(),Map(ba -> 2, bc -> 2, ab -> 1, ac -> 1, aa -> 1, bb -> 2))

为什么我错了?

scala> val map = Map("aa"->1,"ab"->1,"ac"->1,"ba"->2,"bb"->2,"bc"->2)
map: scala.collection.immutable.Map[String,Int] = Map(ba -> 2, bc -> 2, ab -> 1, ac -> 1, aa -> 1, bb -> 2)

scala> map.foreach(p=>if (p._1.startsWith("a")) println(p._1))
ab
ac
aa

scala> map.span(p=> p._1.startsWith("a"))
res30: (scala.collection.immutable.Map[String,Int], scala.collection.immutable.Map[String,Int]) = (Map(),Map(ba -> 2, bc -> 2, ab -> 1, ac -> 1, aa -> 1, bb -> 2))

1 个答案:

答案 0 :(得分:4)

当给定的谓词为false时,

"ba" 会停止,这会立即发生,因为第一个键是Map,这会让您留空partition

您实际上在寻找scala> val map = Map("aa" -> 1, "ab" -> 1, "ac" -> 1, "ba" -> 2, "bb" -> 2, "bc" -> 2) map: Map[String,Int] = Map(ba -> 2, bc -> 2, ab -> 1, ac -> 1, aa -> 1, bb -> 2) scala> map.partition(p => p._1.startsWith("a")) res1: (Map[String,Int], Map[String,Int]) = (Map(ab -> 1, ac -> 1, aa -> 1),Map(ba -> 2, bc -> 2, bb -> 2))

{
  "timestamp": 1498657046424,
  "status": 403,
  "error": "Forbidden",
  "message": "Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.",
  "path": "/contextPath/"
}

(剪辑签名以使REPL输出更具可读性)