Scala在Map列表中查找最后一个元素

时间:2016-11-11 14:05:35

标签: scala mapping

我的系统允许用户搜索" Stock"数据显示每个数据。目前,他们可以搜索库存清单中的最小值和最大值。我试图做到这一点,他们可以找到"当前"股票价格,所以列表尾部的最后一个元素。 我之前有过这个,但是这不符合我的映射列表;

// last element
  def lastif(ls:List[Int]):Int = {
    if(ls.tail == Nil)
      ls.head
    else
      lastif(ls.tail)
  }

这就是我所拥有的,包括底层不起作用的

 def allStockLevel(team: String): (String, List[Int]) =
    (team, mapdata.get(team).getOrElse(List.empty))


  //Shows Highest Stock
  def highestStockLevel(stock: String): (String, Int) =
    (stock, mapdata.get(stock).map(_.max).getOrElse(0))

  //Shows the Lowest Stock
  def lowestStockLevel(stock: String): (String, Int) =
  (stock, mapdata.get(stock).map(_.min).getOrElse(0))


  //Show last element in the list, most current
  def currentStockLevel (team: String): (String, Int) = {
    if (team.tail == Nil)
      team.head
    else
      currentStockLevel(ls.tail)
  }

相关处理程序

 // handlers for menu options
  def handleOne(): Boolean = {
    mnuShowPoints(currentPoints)
    true
  }

相关功能

  def mnuShowSingleDataStock(f: (String) => (String,Int)) = {
    print("Stock>")
    val data = f(readLine)
    println(s"${data._1}: ${data._2}")
  }

正在从txt文件中读取列表

    // read data from file
  val mapdata = readFile("data.txt")


 // UTILITY FUNCTIONS
  //GETS THE DATA FROM THE DATA.TXT
  def readFile(filename: String): Map[String, List[Int]] = {
    processInput(Source.fromFile(filename).getLines)
  }
  def processInput(lines: Iterator[String]): Map[String, List[Int]] = {
    Try {
      lines.foldLeft(Map[String, List[Int]]()) { (acc, line) =>

        val splitline = line.split(",").map(_.trim).toList
        acc.updated(splitline.head, splitline.tail.map(_.toInt))
      }
    }.getOrElse {
      println("Sorry, an exception happened.")
      Map()
    }
  }

1 个答案:

答案 0 :(得分:0)

如果您的地图数据如下:

javascript:(function() {

   function getMessage() {
       if(morning) {
          return "Good Morning";
       } else if(evening) {
          return "Good Evening";
       }
   }

    function myAlert() {
       alert(getMessage());
    }

    myAlert();

})()

然后在每个条目中找到最后一个数字,如:

a,1,2
b,2,3
c,4,6

或者只使用mapdata的键:

  //Show last element in the list, most current
  def currentStockLevel (list: (String,List[Int]) ): (String, Int) = {
    if (list._2.tail == Nil)
      (list._1,list._2.head)
    else
      currentStockLevel(list._1,list._2.tail)
  }

mapdata.map(currentStockLevel).foreach(println)