CallMePedro
CallMePedro

Reputation: 91

Kotlin sumBy function with condition

Instead of using ifs and loops I would like to use sumBy function and give it a statement. Where to add condition?

val counter = list.sumBy {it.amount}

where amount is field from the list.

Where to add for example if(it.flag == true) statement?

Or just use streams?

Upvotes: 1

Views: 2963

Answers (2)

Pawan Soni
Pawan Soni

Reputation: 936

If you have an array by name "amount" the list then items sum will we done by this method.

 val amount= listOf(10, 20, 30)
    println(amount.sumBy { it })

Upvotes: 0

IR42
IR42

Reputation: 9682

val counter = list.sumBy { if (it.flag) it.amount else 0 }

or

val counter = list.asSequence().filter { it.flag }.sumBy { it.amount }

asSequence() for using sequence to prevent creataion an intermediate collection in filter function

Upvotes: 6

Related Questions