αƞjiβ αƞjiβ - 2 months ago 12
Scala Question

Comparing two maps key with possibility of None and null in scala

I have this two

Map[String, String]
and I need to create new map with updated value. Update is done if second Map have new key or non-null value or value greater than of first Map.

For example:

Updating Scenario


  • if
    FirstMap("key1" -> "123")
    and
    SecondMap("key1" -> "456")
    then
    ResultMap("key1" -> "456")

  • if
    FirstMap("key1" -> null)
    and
    SecondMap("key1" -> "value1")
    then
    ResultMap("key1" -> "value1")

  • if
    FirstMap()
    and
    SecondMap("key1" -> "value1")
    then
    ResultMap("key1" -> "value1")



Non-Updating Scenario


  • if
    FirstMap("key1" -> "value1")
    and
    SecondMap()
    then
    ResultMap("key1" -> "value1")

  • if
    FirstMap("key1" -> "value1")
    and
    SecondMap("key1" -> null)
    then
    ResultMap("key1" -> "value1")

  • if
    FirstMap("key1" -> "789")
    and
    SecondMap("key1" -> "456")
    then
    ResultMap("key1" -> "789")



So far I have code below:

val currentFieldValue = currentDetail.get(field).get
val newFieldValue = newDetail.get(field).get

currentFieldValue match {
case null if newFieldValue != null => currentDetail ++ Map(s"$field" -> s"$newFieldValue")
case _ if newFieldValue != null && newFieldValue.toInt > currentFieldValue.toInt => currentDetail ++ Map(s"$field" -> s"$newFieldValue")
case _ => currentDetail
}


Any suggestion on how to accommodate
None
state i.e. when key itself itsn't there?

Answer

map.get(key) returns Option pattern match on the option and create as many relevant cases as you want

(currentDetail.get(field), newDetail.get(field)) match {
  case (Some(null), Some(null)) =>
  case (Some(null), Some(value)) =>
  case (Some(value), Some(null)) => 
  case (Some(value), None) =>
  case (None, Some(value)) =>
  case (None, None) =>
  case (_, _) =>
}