Scala过滤一个序列以映射符合和不符合过滤条件的元素

mic*_*ele 2 scala filter

我有一个字符串序列:

val results = Seq("", "one", "two", "three")
Run Code Online (Sandbox Code Playgroud)

使用两个过滤器,我得到:

val emptyStrings: Seq[String] = results.filter( s => s.isEmpty )
val notEmptyStrings: Seq[String] = results.filterNot( s => s.isEmpty )
Run Code Online (Sandbox Code Playgroud)

是否可以使用一个过滤器 a Map[Boolean, Seq[String]]

  • 键 = isEmpty 真/假
  • values = 空或非空字符串

And*_*yuk 5

$ scala
Welcome to Scala 2.13.0 (OpenJDK 64-Bit Server VM, Java 1.8.0_262).
Type in expressions for evaluation. Or try :help.

scala> val results = Seq("", "one", "two", "three")
results: Seq[String] = List("", one, two, three)

scala> results.groupBy(_.isEmpty)
res0: scala.collection.immutable.Map[Boolean,Seq[String]] = HashMap(false -> List(one, two, three), true -> List(""))
Run Code Online (Sandbox Code Playgroud)

更好的选择是使用partitiondue 它返回一个具有 2 个值的元组而不是一个映射:

scala> results.partition(_.isEmpty)
res1: (Seq[String], Seq[String]) = (List(""),List(one, two, three))
Run Code Online (Sandbox Code Playgroud)

甚至更好地将结果与命名值进行模式匹配:

scala> val (emptyStrings, nonEmptyStrings) = results.partition(_.isEmpty)
emptyStrings: Seq[String] = List("")
nonEmptyStrings: Seq[String] = List(one, two, three)
Run Code Online (Sandbox Code Playgroud)