Scala filter a sequence to map with elements that respect and not respect filter condition

Viewed 553

I have a Sequence of Strings:

val results = Seq("", "one", "two", "three")

With two filter I get:

val emptyStrings: Seq[String] = results.filter( s => s.isEmpty )
val notEmptyStrings: Seq[String] = results.filterNot( s => s.isEmpty )

Is it possible to get with one filter a Map[Boolean, Seq[String]] with:

  • key = isEmpty true/false
  • values = empty or not empty strings
1 Answers
$ 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(""))

A better option would be usage of partition due it returns a tuple with 2 values instead of a map:

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

or even better to pattern match the result to named values:

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