Kotlin mutableMap foreach

My question is more for understanding the documentation. He says:

fun <K, V> Map<out K, V>.forEach(
action: (Entry<K, V>) -> Unit)

However, I do not understand how to implement it. How do I get the key and value inside the loop?

I want to sum for each item in listItemsthe price value. Map associates a string with an item

data class Item(val name: String, val description: String, val price: String, val index: Int)

Imagine what it listItemscontains:

listItems ["shirt"] → name: shirt, description: lorem ipsum, price: 10, index: 0

listItems ["shoes"] → name: shoes, description: lorem ipsum, price: 30, index: 0

Thus, the code will look something like this:

var total: Int = 0
listItems.forEach {
       total += parseInt(value.price)
    }

However, I do not understand how to access this documentation- valuerelatedV

+6
source share
2 answers

, forEach { ... }, Entry<K, V>, , value:

listItems.forEach { total += parseInt(it.value.price) }

, :

listItems.forEach { entry -> total += parseInt(entry.value.price) }

, Kotlin 1.1, lambdas:

listItems.forEach { (_, value) -> total += parseInt(value.price) }

, sumBy { ... }:

val total = listItems.entries.sumBy { parseInt(it.value.price) }
+12

, forEach, sumBy fold.

, value Map<K,V>. , sum, - :

val total = listItems.values.sumBy{ it.price.toInt() }

var.

+4
source

Source: https://habr.com/ru/post/1015727/


All Articles