簡體   English   中英

從 Scala 中的 Map[List()] 返回所有元素

[英]Returning all elements from a Map[List()] in Scala

我對 Scala 非常陌生,所以如果聽起來有點基本,我深表歉意。 從事大學作業,似乎找不到任何類似的問題。

編輯:這個 function 的想法是我通過一串數據並將其分成單獨的元素。 據我所知,事情正在與包含正確數據類型和正確信息的列表正確分離。

所以我創建了一個返回 Map[String, List[(Int, String, Float)]] 的 function

function 做其他事情,但為了簡短起見,一旦我建立了列表,這就是我構建 map 並返回它的方式:-

val newMap = Map(name -> newList2.toList)

newMap

我可以 newMap.foreach 循環通過 map 並找到我的所有元素。 這按預期工作: -

(Sample Key,List((3,PlaceName1,2.7)))
(Sample Key,List((2,PlaceName1,3.8)))
(Sample Key,List((1,PlaceName1,0.75)))

我只是想調用這個 function 並將 map 保存到一個新變量中。 我試過這兩種方法: -

val saveMap = separator("1:PlaceName1:0.75,2:PlaceName2:3.8,3:PlaceName3:2.7")

但是,當我嘗試循環瀏覽時,我只得到第一個列表元素:-

(Sample Key,List((1,PlaceName1,0.75)))

我還嘗試使用以下格式的 mapBuffer:-

var mapBuffer: Map[String, List[(Int, String, Float)]] = Map()

mapBuffer = separator("1:PlaceName1:0.75,2:PlaceName2:3.8,3:PlaceName3:2.7")

同樣,我在這里得到的回報是:-

mutated mapBuffer


(Sample Key,List((1,PlaceName1,0.75)))

Being new to Scala but with some experience in Java and C#, it's killing me how I'm returning a Map value, saving it into a map value that is built the same, and it's not coming through. 嘗試了我能找到的地圖和列表的每一次迭代,但在搜索中找不到任何東西。

有人可以提供任何幫助嗎?

編輯:

這是 function 的完整代碼以及我如何嘗試調用它。

    def separator(data:String): Map[String, List[(Int, String, Float)]] = {
  //Route name will be worked out later. For now, this is a sample.
  val sampleRouteName = "First Route"

  //Stage list will hold each list entry
  val stageList = ListBuffer[(Int, String, Float)]()

  //Stage list builder will put all the list entries together
  var stageListBuilder = List[(Int, String, Float)]()

  if (data.contains(",")) {
    //Find index of first comma
    val commaIndex = data.indexOf(",")

    //Split everything before the comma off
    val (firstEntry, restOfPhrase) = data.splitAt(commaIndex)

    //Find the index of the colon in the first entry
    val colonIndex = firstEntry.indexOf(":")

    //Split everything before the colon off to just keep the number
    val (number, restOfStage) = firstEntry.splitAt(colonIndex)

    //Get rid of the first colon from the rest of the line
    val restOfStage2 = restOfStage.replaceFirst(":", "")

    //Find the index of the next colon
    val colonIndex2 = restOfStage2.indexOf(":")

    //Split everything before the colon off to just keep the stage name
    val (stageName, restOfStage3) = restOfStage2.splitAt(colonIndex2)

    //Get rid of the colon leaving just the stage length
    val stageLength = restOfStage3.replaceFirst(":", "")

    //Put all of these together into a list line in the builder
    stageListBuilder = List((number.toInt,stageName,stageLength.toFloat))

    //Add the list line from the builder to the list as an element
    stageListBuilder.foreach(line => stageList += line)

    //Call recursive function and remove the comma from the start
    separator(restOfPhrase.replaceFirst(",", ""))
  }
  else if (data.length != 0) {
    //Find index of first colon
    val colonIndex = data.indexOf(":")

    //Split everything before the colon off to just keep the number
    val (number, restOfStage) = data.splitAt(colonIndex)

    //Get rid of the first colon from the rest of the line
    val restOfStage2 = restOfStage.replaceFirst(":", "")

    //Find the index of the next colon
    val colonIndex2 = restOfStage2.indexOf(":")

    //Split everything before the colon off to just keep the stage name
    val (stageName, restOfStage3) = restOfStage2.splitAt(colonIndex2)

    //Get rid of the colon leaving just the stage length
    val stageLength = restOfStage3.replaceFirst(":", "")

    //Put all of these together into a list line in the builder
    stageListBuilder = List((number.toInt,stageName,stageLength.toFloat))

    //Add the list line from the builder to the list as an element
    stageListBuilder.foreach(line => stageList += line)
  }

  //This is a map that accurately contains the key (ie. GCU Route) and a list of the routes.
  val routeMap = Map(sampleRouteName -> stageList.toList)

  //To test that the list has all the elements (CURRENTLY WORKING)
  routeMap.foreach(line => println("TEST - " + line))

  //Return the map
  routeMap
}

//val saveMap = separator("1:City Chambers:0.75,2:Velodrome:3.8,3:People's Palace:2.7")

//Create new map buffer
var mapBuffer: Map[String, List[(Int, String, Float)]] = Map()

//Call separator function
mapBuffer = separator("1:City Chambers:0.75,2:Velodrome:3.8,3:People's Palace:2.7")

//Test that each element is in the list (CURRENTLY NOT WORKING)
mapBuffer.foreach(line => println(line))

正如您所提到的,您使用的密鑰與 Map 的密鑰相同。 假設我們有這樣的分隔符方法:

val str = "1:PlaceName1:0.75,2:PlaceName2:3.8,3:PlaceName3:2.7"

def separator(str: String): List[(String, (Int, String, Float))] =
  str.split(",").map(_.split(":")).toList.map(_.toList).collect {
    case ii :: s :: d :: Nil =>
      "Sample Key" -> (ii.toInt, s, d.toFloat)
  }


separator(str).foearch(println)
// result:
(Sample Key,(1,PlaceName1,0.75))
(Sample Key,(2,PlaceName2,3.8))
(Sample Key,(3,PlaceName3,2.7))

如果我們將結果轉換為 Map,我們會丟失一些具有相同鍵的元素,在這種情況下,示例鍵:

def separator1(str: String): Map[String, List[(Int, String, Float)]] =
  str.split(",").map(_.split(":")).toList.map(_.toList).collect {
    case ii :: s :: d :: Nil =>
      "Sample Key" -> List((ii.toInt, s, d.toFloat))
  }.toMap

separator1(str).foreach(println)
// result:
// (Sample Key,List((3,PlaceName3,2.7)))

所以我們不能擁有與 Map 的 KEY 相同的密鑰。 Map 的 KEY 應該是唯一的。

case class Aname(a: Int, b: String, c: Float)

def separator2(str: String): Map[String, List[Aname]] =
  str.split(",").map(_.split(":")).toList.map(_.toList).collect {
    case ii :: s :: d :: Nil =>
      Aname(ii.toInt, s, d.toFloat)
  }.groupBy(_.b)

separator2(str).foreach(println)

// result:
// (PlaceName3,List(Aname(3,PlaceName3,2.7)))
// (PlaceName2,List(Aname(2,PlaceName2,3.8)))
// (PlaceName1,List(Aname(1,PlaceName1,0.75)))

你可以在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM