Steven segal - 1 year ago 47
Java Question

Calculations in a map list

I have multiple lists stored as follows:

``````Data1 -> 2,100
Data2 -> 5,300
``````

And so far I have the ability to insert these into a txt file and read them out again. However I am not sure how to do a calculation so that it displays the first value times the second. This is what I want:

``````Data1 -> 200
Data2 -> 1500
``````

I thought I might have been able to modify my below code (cut out irrelevant code)
`mapdata2`
is stored as a
`Map(String, List[Int])`
:

``````  val mapdata2 = readFile("newDataFile.txt")

//11 view newly created stocks
def handleEleven(): Boolean = {
mnuShowPoints(currentStockFor2)
true
}
def mnuShowPoints(stock:() => Map[String,List[Int]]) = {
stock() foreach {case (x,y) => println(s"\$x: \$y")}
}
// sort map by value in descending order -
def currentStockFor2():Map[String,List[Int]] = {
ListMap(mapdata2.toSeq.sortWith(_._1 < _._1):_*)
}
``````

I am not sure how to approach this problem, I have tried:

``````ListMap(mapdata2.map(x=>x*x)
``````

thinking this may have multiplied the first value by the other value but It does not. I need to get a better understanding of how this works. I do not understand how to do it, So i try a few methods until I can find what works. I am not looking for someone to do the work for me, just help me understand. Thanks

If you are trying to map over the values in your `Map` you could do something like this:

``````scala> val myMap = Map("Data1" -> (2,100), "Data2" -> (3,500))
myMap: scala.collection.immutable.Map[String,(Int, Int)] = Map(Data1 -> (2,100), Data2 -> (3,500))

scala> val newMap = myMap.mapValues(x => x._1 * x._2)
newMap: scala.collection.immutable.Map[String,Int] = Map(Data1 -> 200, Data2 -> 1500)
``````

Or if you want `List`s in your map, you would do something like this:

``````scala> val myMap = Map("Data1" -> List(2,100), "Data2" -> List(3,500, 10))
myMap: scala.collection.immutable.Map[String,List[Int]] = Map(Data1 -> List(2, 100), Data2 -> List(3, 500, 10))

scala> val newMap = myMap.mapValues(_.reduce(_*_))
newMap: scala.collection.immutable.Map[String,Int] = Map(Data1 -> 200, Data2 -> 15000)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download