我有两个Map[String, String]
,我需要创建具有更新值的新地图。如果第二个Map具有新的键或非空值或大于第一个Map的值,则完成更新。
例如:
更新方案
FirstMap("key1" -> "123")
和SecondMap("key1" -> "456")
则ResultMap("key1" -> "456")
FirstMap("key1" -> null)
和SecondMap("key1" -> "value1")
则ResultMap("key1" -> "value1")
FirstMap()
和SecondMap("key1" -> "value1")
则ResultMap("key1" -> "value1")
非更新方案
如果FirstMap("key1" -> "value1")
和SecondMap()
那么
ResultMap("key1" -> "value1")
如果FirstMap("key1" -> "value1")
和SecondMap("key1" -> null)
则ResultMap("key1" -> "value1")
如果FirstMap("key1" -> "789")
和SecondMap("key1" -> "456")
则ResultMap("key1" -> "789")
到目前为止,我的代码如下:
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
}
关于如何容纳None
状态的任何建议,即关键本身不存在?
答案 0 :(得分:1)
map.get(key)
在选项上返回Option
模式匹配,并根据需要创建任意数量的相关案例
(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 (_, _) =>
}
答案 1 :(得分:1)
这里的替代方法是完整的比较功能(带调试信息):
def compare(currentDetail: Map[String, String], newDetail: Map[String, String]): Map[String, String] = {
var resMap = Map[String, String]()
currentDetail.keys.foreach { field =>
val currentField = currentDetail.get(field)
val newField = newDetail.get(field)
resMap = resMap + {
(currentField, newField) match {
case (Some(null), Some(newFieldValue: String)) =>
println("null and not null")
(s"${field}" -> newFieldValue)
case (Some(currentFieldValue), Some(null)) =>
println("not null and null")
(s"${field}" -> currentFieldValue)
case (None, Some(newFieldValue)) =>
println("none and not null")
(s"${field}" -> newFieldValue)
case (Some(currentFieldValue), None) =>
println("not null and none")
(s"${field}" -> currentFieldValue)
case (Some(currentFieldValue), Some(newFieldValue)) if newFieldValue.toInt > currentFieldValue.toInt =>
println("not null not null if new bigger then current")
(s"${field}" -> newFieldValue)
case (Some(currentFieldValue), Some(newFieldValue)) if newFieldValue.toInt <= currentFieldValue.toInt =>
println("not null not null if new less or equal to current")
(s"${field}" -> currentFieldValue)
}
}
}
resMap
}
答案 2 :(得分:1)
def combine(m1: Map[String,String], m2: Map[String,String]): Map[String,String] =
(m1.keys ++ m2.keys).toSet.map{ k: String =>
k -> Seq(Option(m1.getOrElse(k,"")), Option(m2.getOrElse(k,"")), Some(""))
.flatten.sorted.reverse.head
}.toMap
"456" > "123"
对String
和Int
都适用。如果您有两个字符串"99"
和"101"
怎么办?如果您需要进行数字比较,则需要更多代码才能在String
- &gt; Int
- &gt; String
之间传输。