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

but I want to get "abc" only

Is there a scala way to skip nulls?

4
  • 1
    As the old joke goes, "Doctor, doctor, it hurts when I do this." "So, don't do that." Use Option[String] as your type, and None instead of null. Commented Jan 28, 2014 at 1:44
  • 1
    I'd love to do so but these nulls come from Java code. Is this better: Seq(Option("abc"), Option(null)).flatMap(s => s).mkString(" ")? Commented Jan 28, 2014 at 1:55
  • Try it that way, then by filtering, then by changing the Java code. See which is faster while remaining correct. Commented Jan 28, 2014 at 1:57
  • 1
    @NSF, flatMap(s=>s) can be written more succinctly as flatten. Commented Jan 28, 2014 at 2:25

3 Answers 3

19
scala> val seq = Seq("abc", null, "def")
seq: Seq[String] = List(abc, null, def)

scala> seq.flatMap(Option[String]).mkString(" ")
res0: String = abc def
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the flatMap approach. This is what I would expect out of idiomatic Scala. It's also good to know that Option(null) reliably returns "None"
15

There's always Seq("abc", null).filter(_ != null).mkString(" ")

2 Comments

Seq("abc", null).iterator.filter(_ != null).mkString(" ") to avoid building the intermediate collection.
@KevinWright Current versions of Scala have withFilter for that, don't they? Update: Just tried it - apparently mkString doesn't work directly with withFilter
1

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 resulting in Seq[Option[String]]. collect then essentially does a filter and map, discarding the None values and leaving only the unwrapped Some values.

1 Comment

Seq("abc", null).flatMap(Option(_)).mkString(" "). Flatten does what you want it to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.