简体   繁体   English

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

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

I'm VERY new to Scala so apologies if anything sounds a bit basic.我对 Scala 非常陌生,所以如果听起来有点基本,我深表歉意。 Working on a uni assignment and can't seem to find any similar questions around.从事大学作业,似乎找不到任何类似的问题。

EDIT: The idea of this function is that I pass through a string of data and separate it up into individual elements.编辑:这个 function 的想法是我通过一串数据并将其分成单独的元素。 From what I can tell, things are being separated correctly with the lists holding the correct data types and correct information.据我所知,事情正在与包含正确数据类型和正确信息的列表正确分离。

So I've created a function that returns a Map[String, List[(Int, String, Float)]]所以我创建了一个返回 Map[String, List[(Int, String, Float)]] 的 function

The function does other things, but to keep it short, once I've build the list this is how I build the map and return it: - function 做其他事情,但为了简短起见,一旦我建立了列表,这就是我构建 map 并返回它的方式:-

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

newMap

I can newMap.foreach to cycle through the map and find all of my elements.我可以 newMap.foreach 循环通过 map 并找到我的所有元素。 This works as expected: -这按预期工作: -

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

I am simply trying to call this function and save the map into a new variable.我只是想调用这个 function 并将 map 保存到一个新变量中。 I have tried this two ways: -我试过这两种方法: -

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

However when I try to cycle through this, I only get the first list element: -但是,当我尝试循环浏览时,我只得到第一个列表元素:-

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

I have also tried to use a mapBuffer in the format of: -我还尝试使用以下格式的 mapBuffer:-

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

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

Again, all I get as my return here is: -同样,我在这里得到的回报是:-

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. 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. Tried every iteration of maps and lists I could find and can't find anything on this from searching.尝试了我能找到的地图和列表的每一次迭代,但在搜索中找不到任何东西。

Is anyone able to offer any assistance?有人可以提供任何帮助吗?

EDIT:编辑:

Here is the whole code for the function and how I am attempting to call it.这是 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))

As you mentioned you are using same keys as a key of a Map.正如您所提到的,您使用的密钥与 Map 的密钥相同。 Let's imagine we have separator method like this:假设我们有这样的分隔符方法:

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))

if we convert our result to a Map we lose some elements with same key in this case Sample Key:如果我们将结果转换为 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)))

So we cannot have the same keys as KEY of a Map.所以我们不能拥有与 Map 的 KEY 相同的密钥。 The KEYs of a Map should be a unique. 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)))

You can play with ithere你可以在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM