我想在Scala文件中搜索给定状态树的列表。斯卡拉地图不迭代到所有元素
下面是示例文件(制表符分隔): -
Quercus acerifolia mapleleaf oak MN
Quercus _acutidens CA
Quercus acutissima sawtooth oak AL,GA,LA,MD,MS,NC,PA,VA
Quercus agrifolia California live oak CA
Quercus alba white oak AL,AR,CT,DC,DE,FL,GA,IA,IL,IN,KS,KY,LA
Quercus ajdfensis Ajo Mountain scrub oak ,MN
我的代码: -
//declaring package
package HW10
//declaring object
object TreesStub {
//importing Source package for files import
import scala.io.Source
//assigning the file path to filename variable
val fileName = "trees.tsv"
//defining Main function
def main(args: Array[String]): Unit = {
//reading source file from a file which is tabe separated
val treeList: List[String] = Source.fromFile(fileName).getLines.toList
//calling searchTrees method for a given State
searchTrees("MN", treeList)
//searchTrees method logic for a given State and print it
def searchTrees(state: String, trees: List[String]): Unit = {
//defining mutable empty map collection as "states"
var states = collection.mutable.Map[String, String]()
//Searching the tree list for a given state and adding the map and //tree list to the states map collection
trees.map(x => (x.split("\t", -1))).filter((_.length > 2)).map(x =>
//using try catch block for handling match not found exception
try {
if (x(2).contains(state)) states += (state -> x(0))
}
catch {
//exception if caught to None
case e: Exception => println(s"None")
})
//printing map "states" values
states.foreach(println)
}
}
}
输出我得到如下: - (MN,Quercus acerifolia)
预期输出: - (州名,树名单)
(MN,Quercus acerifolia)
(MN,Quercus ajdfensis)
我只能打印一个不能打印所有比赛的比赛。不知道代码中出了什么问题?看起来地图只迭代一次而不是所有的匹配。请让我知道如何打印所有比赛?
非常感谢。我认为你是对的,我认为地图将允许scala中的单个键的多个值,而不是这种情况。我们需要多个地图。我使用列表处理。 – Issaq