繁体   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