对列表中的数字子集求和 [英] Sum a subset of of numbers in a list

查看:109
本文介绍了对列表中的数字子集求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin中,有没有一种方法可以对经过过滤的数字列表进行sum()操作,而无需先实际过滤掉元素?

Is there a way in Kotlin for doing the sum() operation on a filtered list of numbers, without actually filtering out the elements first?

我正在寻找这样的东西:

I'm looking for something like this:

val nums = listOf<Long>(-2, -1, 1, 2, 3, 4)
val sum = nums.sum(it > 0)

推荐答案

您可以使用Iterable<T>.sumBy:

/**
 * Returns the sum of all values produced by [selector] function applied to each element in the collection.
 */
public inline fun <T> Iterable<T>.sumBy(selector: (T) -> Int): Int {
    var sum: Int = 0
    for (element in this) {
        sum += selector(element)
    }
    return sum
}

您可以将一个函数传递给它,该函数将负值转换为0.因此,它对列表中大于0的所有值求和,因为加0对结果无效.

You can pass a function to it where the function transforms negative value to 0. So, it sums up all values in the list which is greater than 0 since adding 0 makes no effect to the result.

val nums = listOf<Long>(-2, -1, 1, 2, 3, 4)
val sum = nums.sumBy { if (it > 0) it.toInt() else 0 }
println(sum)    //10

如果需要返回Long值,则必须为Long编写扩展名,就像

If you require a Long value back, you have to write an extension for Long just like Iterable<T>.sumByDouble.

inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long {
    var sum: Long = 0
    for (element in this) {
        sum += selector(element)
    }
    return sum
}

然后,可以取消toInt()转换.

 nums.sumByLong { if (it > 0) it else 0 }

如@Ruckus T-Boom所建议,可以使用Long.coerceAtLeast()简化if (it > 0) it else 0,它返回值本身或给定的最小值:

As suggested by @Ruckus T-Boom, if (it > 0) it else 0 can be simplified using Long.coerceAtLeast() which returns the value itself or the given minimum value:

nums.sumByLong { it.coerceAtLeast(0) }

这篇关于对列表中的数字子集求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆