在Scala的HashMap中查找键的最后一个值-如何以函数样式编写
我想在一个键之后搜索hashmap,如果找到了该键,请给我找到的键值的最后一个值。到目前为止,我的解决方案如下:在Scala的HashMap中查找键的最后一个值-如何以函数样式编写,scala,Scala,我想在一个键之后搜索hashmap,如果找到了该键,请给我找到的键值的最后一个值。到目前为止,我的解决方案如下: import scala.collection.mutable.HashMap object Tmp extends Application { val hashmap = new HashMap[String, String] hashmap += "a" -> "288 | object | L" def findNameInSymboltable(name
import scala.collection.mutable.HashMap
object Tmp extends Application {
val hashmap = new HashMap[String, String]
hashmap += "a" -> "288 | object | L"
def findNameInSymboltable(name: String) = {
if (hashmap.get(name) == None)
"N"
else
hashmap.get(name).flatten.last.toString
}
val solution: String = findNameInSymboltable("a")
println(solution) // L
}
是否有一种功能性的方式可以节省LOC的开销?无法让您的示例正常工作。但也许像这样的东西能起作用
hashmap.getOrElse("a", "N").split(" | ").last
“getOrElse”至少可以为您保存if/else检查。无法让您的示例正常工作。但也许像这样的东西能起作用
hashmap.getOrElse("a", "N").split(" | ").last
“getOrElse”将至少为您保存if/else检查。如果您的“N”
是用于显示而不是用于计算,您可以将我们拖出无中没有此类“a”
的事实,直到显示:
val solution = // this is an Option[String], inferred
hashmap.get("a"). // if None the map is not done
map(_.split(" | ").last) // returns an Option, perhaps None
也可以这样写:
val solution = // this is an Option[String], inferred
for(x <- hashmap.get("a"))
yield {
x.split(" | ").last
}
如果您的“N”
是用于显示而不是用于计算,您可以将我们拖动到无中没有这样的“a”
,直到显示:
val solution = // this is an Option[String], inferred
hashmap.get("a"). // if None the map is not done
map(_.split(" | ").last) // returns an Option, perhaps None
也可以这样写:
val solution = // this is an Option[String], inferred
for(x <- hashmap.get("a"))
yield {
x.split(" | ").last
}
我喜欢Scala的简洁。是的,喜欢这种语法糖,学到了一些非常有用的东西。我喜欢Scala的简洁。是的,喜欢这种语法糖,学到了一些非常有用的东西。你为什么不在地图上存储一个Seq?为什么不在地图上存储一个Seq?