Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace null values in a list with another value in Scala

I'm attempting to replace the null elements of a Scala list with an empty value using map. I currently have:

val arr = Seq("A:B|C", "C:B|C", null)
val arr2 = arr.map(_.replaceAll(null, "") )

This gives me a NullPointerExpection. What is the best way to do this?

like image 901
Feynman27 Avatar asked Nov 28 '25 01:11

Feynman27


1 Answers

You're trying to replace a null character in a string instead of replacing a null string in Seq. So here is a correct way:

val arr2 = arr.map(str => Option(str).getOrElse(""))

The Option here will produce Some(<your string>) if the value is not null and None otherwise. getOrElse will return your string if it's not null or empty string otherwise.

like image 147
Zyoma Avatar answered Nov 29 '25 17:11

Zyoma