At the moment I have
val orders = new HashMap[Int, Int]
orders.put(36, 110)
orders.put(35, 90)
orders.put(34, 80)
orders.put(33, 60)
I would like to keep a running so that the end mapping appears as follows
36 -> 110
35 -> 200
34 -> 280
33 -> 340
At the moment I do this imperatively as follows
val keys = orders.keys.toList.sortBy(x => -x)
val accum = new HashMap[Int, Int]
accum.put(keys.head, orders(keys.head))
for (i <- 1 to keys.length - 1) {
accum.put(keys(i), orders(keys(i)) + accum(keys(i-1)))
}
accum.foreach {
x => println(x._1, x._2)
}
Is there a more functional way of doing this using mapping, folding etc? I would be able to do it with a straight List but the can’t quite wrap my head around how to do this with HashMap
Edit: Ordering is important. The left column (36, 35, 34, 33) needs to be in descending order
For the record, here is a solution using the
initsmethod: