First of all, the code snippet you provided won't compile, because of Null in values and keys not swapped in quotes to be considered as string. I've replaced values with Option:
val mapData: Map[String, Option[Int]] = Map("AA1" -> Some(1), "AA2" -> Some(2), "AA3" -> None, "AA4" -> None)
val max = mapData.values.flatten.max
val (result, _) = mapData.toList.foldLeft(Map.empty[String, Int] -> (max + 1)) {
case ((accumulator, nextMax), (key, None)) =>
((accumulator + (key -> nextMax)), nextMax + 1)
case ((accumulator, nextMax), (key, Some(value))) =>
((accumulator + (key -> value)), nextMax)
}
println(result)
which will print next result: Map(AA1 -> 1, AA2 -> 2, AA3 -> 3, AA4 -> 4)
Scatie example: https://scastie.scala-lang.org/ltmhh3tuQCWf2deaLboK9w
UPDATE:
As @Tomer Shetah correctly stated in comments section - max is not safe, because List[Int].empty.max will throw exception. Replaced with maxOption
val mapData: Map[String, Option[Int]] = Map("AA1" -> Some(1), "AA2" -> Some(2), "AA3" -> None, "AA4" -> None)
val max = mapData.values.flatten.maxOption.getOrElse(0) //safer with maxOption
val (result, _) = mapData.toList.foldLeft(Map.empty[String, Int] -> (max + 1)) {
case ((accumulator, nextMax), (key, None)) =>
((accumulator + (key -> nextMax)), nextMax + 1)
case ((accumulator, nextMax), (key, Some(value))) =>
((accumulator + (key -> value)), nextMax)
}
println(result)
Scatie: https://scastie.scala-lang.org/iiSvahIZStyL1MDi0Glsvg