3

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?

1 Answer 1

4

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Short hand notation for filter: .filter(_ != null)

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.