By Alvin Alexander. Last updated: February 21, 2021
In Scala, if you have an array or list of strings and need to remove all of the empty/blank strings, just use the filter method on the array/list and the String class nonEmpty
method. Here’s an example in the Scala REPL:
scala> val x = List("foo", "", "bar", "") x: List[String] = List(foo, "", bar, "") scala> val y = x.filter(_.nonEmpty) y: List[String] = List(foo, bar)
As shown in that example, using filter
and nonEmpty
results in a new list named y where all of the empty strings have been removed from the list.