Reputation: 311
My question is more to understand the documentation. It say's:
fun <K, V> Map<out K, V>.forEach(
action: (Entry<K, V>) -> Unit)
However I don't understand how to implement it. How I get the Key and Value inside the loop?
I want to sum for each item in listItems
the value of the price. The map associates a string with an item
data class Item(val name: String, val description: String, val price: String, val index: Int)
Imagine listItems
contains this:
listItems["shirt"]-> name: shirt, description: lorem ipsum, price: 10, index: 0
listItems["shoes"]-> name: shoes, description: lorem ipsum, price: 30, index: 0
So the code would be something like:
var total: Int = 0
listItems.forEach {
total += parseInt(value.price)
}
However I don't understand how to acces this value
refering to the V
of the documentation
Upvotes: 13
Views: 13312
Reputation: 147951
The lambda that you pass to forEach { ... }
accepts an Entry<K, V>
, and you can work with this entry, accessing its value
:
listItems.forEach { total += parseInt(it.value.price) }
Which is equivalent to this using explicit lambda parameter:
listItems.forEach { entry -> total += parseInt(entry.value.price) }
Or, since Kotlin 1.1, you can use destructuring in lambdas:
listItems.forEach { (_, value) -> total += parseInt(value.price) }
If you only need to sum the values, you can use sumBy { ... }
:
val total = listItems.entries.sumBy { parseInt(it.value.price) }
Upvotes: 21
Reputation: 23512
For the some of a collection, instead of using forEach
, I'd suggest going for sumBy
or fold
.
You can get the underlying values by calling value
on the Map<K,V>
.
So to get the sum
you'd do something like this:
val total = listItems.values.sumBy{ it.price.toInt() }
Now there's no need to introduce a mutable var
.
Upvotes: 4