Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - filter out null values in a Array[Map[String,Int]]

Tags:

scala

I have an Array of [Map[String,Int] like this:

val orArray = Array(Map("x" -> 24, "y" -> 25, "z" -> 26), null, Map("x" -> 11, "y" -> 22, "z" -> 33), null, Map("x" -> 111, "y" -> 222, "z" -> 333))

I want to remove the null elements in this array, to get something like:

Array[Map[String,Int]] = (Map("x" -> 24, "y" -> 25, "z" -> 26),  Map("x" -> 11, "y" -> 22, "z" -> 33),  Map("x" -> 111, "y" -> 222, "z" -> 333))

I was trying this so far

orArray.filterNot(p => p.isEmpty)

But it generates a NullPointerException. How could I filter out those two null values?

like image 757
Ignacio Alorre Avatar asked Feb 04 '26 07:02

Ignacio Alorre


1 Answers

You can simply check the null values as

orArray.filter(map  => map != null)

Output:

Map(x -> 24, y -> 25, z -> 26), Map(x -> 11, y -> 22, z -> 33), Map(x -> 111, y -> 222, z -> 333)

Hope this helps!

like image 94
koiralo Avatar answered Feb 05 '26 22:02

koiralo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!