Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin mutableMap foreach

Tags:

kotlin

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

like image 548
eloo Avatar asked Mar 14 '17 11:03

eloo


People also ask

What is MutableMap in Kotlin?

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.


2 Answers

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) }
like image 66
hotkey Avatar answered Sep 27 '22 22:09

hotkey


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.

like image 20
Luka Jacobowitz Avatar answered Sep 27 '22 20:09

Luka Jacobowitz