开发者

Finding the values last values of a key in HashMap in Scala - how to write it in a functional style

I want to search the hashmap after a key and if the key is found give me the last value of the found value of the key. Here is my solution so far:

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

}

Is there maybe a functional style of it which save me the overhead of locs?


Couldn't quite get your example to work. But maybe something like this would do the job?

hashmap.getOrElse("a", "N").split(" | ").last

The "getOrElse" will at least save you the if/else check.


In case your "N" is intended for display and not for computation, you can drag ouround the fact that there is no such "a" in a None until display:

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

Which can alse be written:

val solution = // this is an Option[String], inferred
  for(x <- hashmap.get("a"))
    yield {
      x.split(" | ").last
    }

And finally:

println(solution.getOrElse("N"))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜