Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Scala的HashMap中查找键的最后一个值-如何以函数样式编写_Scala - Fatal编程技术网

在Scala的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

我想在一个键之后搜索hashmap,如果找到了该键,请给我找到的键值的最后一个值。到目前为止,我的解决方案如下:

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?