Home > Net >  Kotlin sum values in object using lambda
Kotlin sum values in object using lambda

Time:11-16

I have a map of Map<String, List<VehicleData>>

data class VehicleData{
  var id: Long? = null, 
  var totalKwh: Double? = null,
}

I group data by kwh

"kwh" to List<VehicleData>

I need to sum up the totalKwh in , my current approach is

//assume that i set the data into vehicleDataMap, vehicleDataMap has format of Map<String, List<VehicleData>>
//how can i do the following in functional way in kotlin?
var list = mutableListOf<Number>()
vehicleDataMap.forEach{
    var sumKwh = 0.0
    it.value.forEach{
        sumKwh = sumKwh.plus(it.totalKwh!!)
    }
    list.add(sumKwh)
}

How can i do the SUM in functional way? like in kotlin lambda

CodePudding user response:

You can use Map.mapValues and Collections.sumOf (or sumByDouble before Kotlin 1.4):

val res: Map<String, Double> = vehicleDataMap.mapValues {
    (_, v) -> v.sumOf { it.totalKwh ?: 0.0 }
}

Or, if you need a List as a result:

val res: List<Double> = vehicleDataMap.values.map {
    it.sumOf { it.totalKwh ?: 0.0 }
}

CodePudding user response:

it.value.sumOf {it.totalKwh!!}

This should work.

  • Related