How to allow mkString to skip null in scala?

scala> Seq("abc", null).mkString(" ") res0: String = abc null 

but I want to get only "abc"

Is there a scala way to skip zeros?

+6
source share
3 answers
 scala> val seq = Seq("abc", null, "def") seq: Seq[String] = List(abc, null, def) scala> seq.flatMap(Option[String]).mkString(" ") res0: String = abc def 
+17
source

Always Seq("abc", null).filter(_ != null).mkString(" ")

+15
source

A combination of Rex's answer and Eric's first comment:

 Seq("abc", null).map(Option(_)).collect{case Some(x) => x}.mkString(" ") 

The first map wraps the values โ€‹โ€‹leading to Seq[Option[String]] . collect , essentially filter and map , discarding the None values โ€‹โ€‹and leaving only the expanded values โ€‹โ€‹of Some .

+1
source

All Articles