user13857520
user13857520

Reputation:

Scala - How to delete Keys of a Scala Map which has Null and Blank Values

I have a below Map which keys contains Null or Blank value. How to drop or filter out these key-value pair from Map using trim for blank. Below I am trying but its not working. Kindly help.

val map = Map("A/B/C" -> null, "E/F/G" -> "", "F/A/D" -> " ", "M/N/O" -> 4, "N/O/P" -> 5)
val filteredMap = map.filterKeys(map(_) != null || map(_) != "".trim)

Upvotes: 0

Views: 1454

Answers (2)

Boris Azanov
Boris Azanov

Reputation: 4481

Your code is not even compilable because you are trying to use _ but you can't shorten expression here. For correct result you should expand lambda expression and replace || to &&:

val filteredMap = map.filterKeys(
  key => Option(map(key)).exists(_.toString.trim().nonEmpty)
) 
// Map(N/O/P -> 5, M/N/O -> 4)

Upvotes: 1

jwvh
jwvh

Reputation: 51271

If you mis-typed and you actually have a Map[String,String] then you're attempt isn't too far off. It just needs a few adjustments.

val map: Map[String,String] =
  Map("A/B/C" -> null, "E/F/G" -> "", "F/A/D" -> " ", "M/N/O" -> "4", "N/O/P" -> "5")

val filteredMap = map.filter(x => x._2 != null && x._2.trim != "")

If, on the other hand, you did not mis-type and you actually have a Map[String,Any] then you should fix that, but I suppose you might get away with something like this.

val filteredMap = map.flatMap{
  case (k:String, v:Int) => Some(k -> v)
  case (_, null) => None
  case (k:String, v:String) if v.trim.nonEmpty => Some(k -> v)
  case _ => None
}

But, really, you should fix that. Type Any is a sign that your design is going off track.

Upvotes: 1

Related Questions