如何在Scala中无需额外变量将Map的NA值替换为0?
Hey there! Let's solve this problem where we need to replace all "NA" values in your Map[Int, String] with "0" without using extra variables. Here's how you can do it in Scala:
Option 1: Use the transform method
The transform method is tailor-made for this scenario—it lets you modify Map values directly by applying a function to each key-value pair. For immutable Maps, it returns a new Map, which we can assign straight back to the original variable (no extra variables needed):
// Your initial Map var colValues: Map[Int, String] = Map(15043 -> "226", 15044 -> "NA", 15045 -> "36", 15046 -> "0", 15047 -> "47", 15048 -> "NA") // Replace "NA" with "0" and reassign to the same variable colValues = colValues.transform((_, value) => if (value == "NA") "0" else value)
Option 2: Use the map method
If you prefer using map, you can destructure each key-value pair and replace the value conditionally:
colValues = colValues.map { case (key, value) => key -> (if (value == "NA") "0" else value) }
After running either of these, your colValues will be exactly what you need:Map(15043 -> "226", 15044 -> "0", 15045 -> "36", 15046 -> "0", 15047 -> "47", 15048 -> "0")
A quick note: If your colValues was declared with val (an immutable variable), you'd need to declare a new val—but since the requirement says no extra variables, using var lets you reassign the updated Map back to the original name without creating a new variable.
内容的提问来源于stack exchange,提问作者Mohd. Mahtab Alam

