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
Kotlin MutableMap is an interface of collection frameworks which contains objects in the form of keys and values. It allows the user to efficiently retrieve the values corresponding to each key. The key and values can be of the different pairs like <Int, String>, < Char, String>, etc.
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) }
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With