본문 바로가기

Android/Kotlin

MutableList

728x90

* sum()

The examples show you how to use sum() function to:

  • sum of all items in the normal List
  • sum of specific field in List of Objects (in need of map())
  • sum of specific field of all values in a Map (in need of map())

Why we need map()?
map() will create a List of quantity first, then we invoke: List<quantity>.sum()

List

We’re gonna use sum() on List<Int> and List<Double> for example.

val nums = listOf(10, 20, 30) println(nums.sum()) // 60

val doubles = listOf(1.05, 2.05, 3.65) println(doubles.sum()) // 6.75

* sumBy()

The examples show you ways to use sumBy() function to:

  • sum (and change value to Int) of all items in the normal List
  • sum of specific Int field in List of Objects (no need map())
  • sum of specific Int field of all values in Map of Objects (no need map())

Why we don’t need map()?
Look at protoype of sumBy() function:

inline fun sumBy(selector: (T) -> Int): Int

You can see that sumBy() receives a selector which indicates the field to be processed.

List

import kotlin.math.roundToInt val nums = listOf(10, 20, 30)

println(nums.sumBy { it }) // 60

println(nums.sumBy { it * 2 }) // 120

val doubles = listOf(1.05, 2.05, 3.65)

println(doubles.sumBy { it.roundToInt() }) // 7

 

728x90

'Android > Kotlin' 카테고리의 다른 글

[BOJ][KOTLIN] 2447 별 찍기 - 10  (0) 2021.11.20
안드로이드 스튜디오 Kotlin Memory Leak Warning("StaticFieldLeak")  (0) 2021.02.16
Subroutine  (0) 2020.06.15