我想使用 sumBy 函数并给它一个语句,而不是使用 ifs 和循环。在哪里添加条件?
val counter = list.sumBy {it.amount}
其中金额是列表中的字段。
在哪里添加示例if(it.flag == true)语句?
还是只使用流?
val counter = list.sumBy { if (it.flag) it.amount else 0 }
Run Code Online (Sandbox Code Playgroud)
或者
val counter = list.asSequence().filter { it.flag }.sumBy { it.amount }
Run Code Online (Sandbox Code Playgroud)
asSequence()用于使用序列来防止在过滤器功能中创建中间集合