Hi Lo
Hi Lo

Reputation: 123

Developing lambda expression

var t = 0
fun sumIntMap(hm: HashMap<Int,Int>) = hm.forEach{ x -> t+=x.value 
}.let { t }

Trying to sum a Hashmap Int values here with a function, I cannot seem to optimize it so that it requires not capturing and needing the temp var (t).

How can I use temp vars in lambdas and return them? Is how I wrote it the only real way (using a let to return the temp var)?

Thanks!

Upvotes: 1

Views: 78

Answers (1)

zsmb13
zsmb13

Reputation: 89678

You can map your HashMap entries to their values to get a List of Ints, and then sum the values in that list:

hm.map { it.value }.sum()

If you have a List instead of a Map, you can also use fold or reduce to do similar things to your original code:

hm.toList().fold(0, { acc, pair -> acc + pair.second })

Upvotes: 4

Related Questions