繁体   English   中英

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

[英]Scala finding the last element in a Map list

我的系统允许用户搜索“股票”数据列表以显示每个数据。 当前,他们可以搜索库存清单中的最小值和最大值。 我正在努力做到这一点,以便他们可以找到“当前”股票价格,因此列表尾部的最后一个元素。 我以前有这个,但是这不符合我的映射列表。

// 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()
    }
  }

如果您的地图数据是这样的:

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

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

  //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)

或者只使用mapdata的键:

def currentStockLevel (list: String ): (String, Int) = {

    def current(list:  List[Int]):Int = {
      if (list.tail == Nil)
        (list.head)
      else
        current(list.tail)
    }

    val res = mapdata.get(list) match {
      case Some(x: List[Int]) => x
      case _ => List.empty
    }

    (list,current(res))
  }


mapdata.map(x => current(x._1)).foreach(println)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM