2

If you have two maps (one is mutable, the other is immutable), how would you multiply the values of one with the corresponding values of the other?

For example:

val testA = scala.collection.mutable.Map("£2" -> 3, "£1" -> 0, 
                  "50p" -> 4, "20p" -> 0, "10p" -> 0, "5p" -> 0)
val testB = scala.collection.immutable.Map("£2" -> 2, "£1" -> 1, 
                  "50p" -> 0.5, "20p" -> 0.2, "10p" -> 0.1, "5p" -> 0.05)

Expecting a result of:

val total = scala.collection.immutable.Map("£2" -> 6, "£1" -> 0, 
                  "50p" -> 2, "20p" -> 0, "10p" -> 0, "5p" -> 0)`
Tzach Zohar
  • 37,442
  • 3
  • 79
  • 85

1 Answers1

2

You can use map to map each value to that value multiplied by the lookup result on testB (or 1.0, if none found)

testA.map { case (k, v) => (k, v * testB.getOrElse(k, 1.0)) }
Tzach Zohar
  • 37,442
  • 3
  • 79
  • 85
  • Excellent! Thank you very much. – Patrick White Apr 24 '17 at 15:53
  • 1
    See also: http://stackoverflow.com/questions/7076128/best-way-to-merge-two-maps-and-sum-the-values-of-same-key - same question (with addition instead of multiplication), with some other interesting answers (specifically, using Scalaz's Semigroup) – Tzach Zohar Apr 24 '17 at 15:54