Maps, Sets, and Grouping
Iterating Map Entries
Visit each key and value in a map.
Iterating Map Entries
MapEntries.scala
object Main {
def main(args: Array[String]): Unit = {
val bonus =
val prices = Map("pad" -> 5, "pen" -> 2, "ink" -> 8)
var total = 0
for ((k, v) <- prices) {
total = total + v + bonus
}
println("entries=" + prices.size)
println("total=" + total)
}
}
object Main {
def main(args: Array[String]): Unit = {
val bonus =
val prices = Map("pad" -> 5, "pen" -> 2, "ink" -> 8)
var total = 0
for ((k, v) <- prices) {
total = total + v + bonus
}
println("entries=" + prices.size)
println("total=" + total)
}
}
object Main {
def main(args: Array[String]): Unit = {
val bonus =
val prices = Map("pad" -> 5, "pen" -> 2, "ink" -> 8)
var total = 0
for ((k, v) <- prices) {
total = total + v + bonus
}
println("entries=" + prices.size)
println("total=" + total)
}
}
map-entries
A `for` over a map binds each entry to a key and value. Summing the values gives one scalar result regardless of entry order.