Scala映射不会迭代到所有元素

时间:2017-04-23 23:59:41

标签: scala

我正在尝试使用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)   

我只能打印一个无法打印所有比赛的比赛。不确定代码中有什么问题?看起来地图只迭代一次而不是所有匹配。请让我知道如何打印所有比赛?

2 个答案:

答案 0 :(得分:1)

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

您是否尝试过搜索MN以外的内容? 你的最后一行是,MN,这可能会弄乱你的字符串比较。

答案 1 :(得分:0)

states是一个地图,一种将每个键映射到单个值的数据结构。因此,如果要为同一个密钥累积多个结果,则映射是错误的数据结构。