You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 20:42:58