Kotlin List sumBy()
Syntax & Examples
Syntax of List.sumBy()
The syntax of List.sumBy() extension function is:
fun <T> Iterable<T>.sumBy(selector: (T) -> Int): IntThis sumBy() extension function of List returns the sum of all values produced by selector function applied to each element in the collection.
✐ Examples
1 Example
In this example,
- We create a list named
listcontaining the integers1, 2, 3, 4, 5. - We apply a selector function
{ it * it }which squares each element of the list. - The
sumByfunction calculates the sum of all squared values. - The sum, which is an integer, is stored in
sum. - Finally, we print the value of
sumto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5);
val sum = list.sumBy { it * it };
println(sum);
}Output
55
2 Example
In this example,
- We create a list named
listcontaining the strings"apple", "banana", "cherry", "date", "elderberry". - We apply a selector function
{ it.length }which calculates the length of each string in the list. - The
sumByfunction calculates the sum of all lengths. - The sum, which is an integer, is stored in
sum. - Finally, we print the value of
sumto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry");
val sum = list.sumBy { it.length };
println(sum);
}Output
31
3 Example
In this example,
- We define a data class
Personwith propertiesnameandage. - We create a list named
peoplecontaining instances ofPerson. - We apply a selector function
{ it.age }which extracts theageproperty of eachPersonobject. - The
sumByfunction calculates the sum of all ages. - The sum, which is an integer, is stored in
sum. - Finally, we print the value of
sumto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
data class Person(val name: String, val age: Int)
val people = listOf(
Person("Alice", 30),
Person("Bob", 25),
Person("Charlie", 40)
);
val sum = people.sumBy { it.age };
println(sum);
}Output
95
Summary
In this Kotlin tutorial, we learned about sumBy() extension function of List: the syntax and few working examples with output and detailed explanation for each example.