我有一个字符串序列:
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]]:
$ 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)
| 归档时间: |
|
| 查看次数: |
142 次 |
| 最近记录: |