如何在Kotlin中汇总整数列表的所有项目?

Fra*_*den 3 kotlin

我有一个整数列表,如:

val myList = listOf(3,4,2)
Run Code Online (Sandbox Code Playgroud)

在Kotlin有没有快速的方法来总结列表的所有值?还是我必须使用循环?

谢谢.

Cru*_*ces 13

上面的答案是正确的,作为补充答案,如果您想对某些属性求和或执行某些操作,您可以像这样使用 sumBy:

总和属性:

data class test(val id: Int)

val myTestList = listOf(test(1), test(2),test(3))

val ids = myTestList.sumBy{ it.id } //ids will be 6
Run Code Online (Sandbox Code Playgroud)

用动作求和

val myList = listOf(1,2,3,4,5,6,7,8,9,10)

val addedOne = myList.sumBy { it + 1 } //addedOne will be 65
Run Code Online (Sandbox Code Playgroud)


小智 8

上面的答案是正确的,但是,如果您还想对对象列表中的所有整数、双精度、浮点数求和,这可以是另一种方式

list.map { it.duration }.sum()
Run Code Online (Sandbox Code Playgroud)

  • 你可以只做 `list.sumOf { it.duration }` (4认同)

Dav*_*uel 7

您可以使用该.sum()功能来总结一个数组或集合中的所有元素Byte,Short,Int,Long,FloatDouble.(docs)

例如:

val myIntList = listOf(3, 4, 2)
myIntList.sum() // = 9

val myDoubleList = listOf(3.2, 4.1, 2.0)
myDoubleList.sum() // = 9.3
Run Code Online (Sandbox Code Playgroud)


Ris*_*ngh 6

sumBy已弃用新sumOf用途

val data = listOf(listOf(1, 2, 3), listOf(4, 5, 6))
println(data.sumOf { it.size }) // 6
println(data.sumOf { innerList -> innerList.sumOf { it } }) //21
println(data.sumOf { innerList -> innerList.sum() }) // 21
Run Code Online (Sandbox Code Playgroud)