[英]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.