Rjj
Rjj

Reputation: 297

How to remove nulls in my list variable?

I have the following list input:

List(List(first, sec, null, null), List(third, null, null))

I need to remove nulls from my list, in order to get:

List(List(first, sec), List(third))

Upvotes: 3

Views: 3864

Answers (2)

Xavier Guihot
Xavier Guihot

Reputation: 61666

Given this list:

val list = List(List("first", "sec", null, null), List("third", null, null))

And the fact that Option(null) gives None, then:

list.map(_.flatMap(Option(_)))

produces:

List(List("first", "sec"), List("third"))

Upvotes: 6

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41957

If you have nested List as

val data = List(List("first", "sec", null, null), List("third", null, null))

Then use map and filterNot as

data.map(_.filterNot(_ == null))
//res0: List[List[String]] = List(List(first, sec), List(third))

Or you can use map and filter as

data.map(_.filter(_ != null))
//res0: List[List[String]] = List(List(first, sec), List(third))

I hope the answer is helpful

Upvotes: 7

Related Questions