我有一个对象列表
data class OldFormat(ShiftId: Int, NozzleValue: Int, NozzleId: Int , UserId: Int)
我要按两个字段“ shiftId和userId”进行分组,然后从同一组的最小值中减去每个组的最大值,然后
对结果求和,然后将其转换为具有此类的新对象:
data class NewFormat(ShiftId: Int, NozzleValue: Int, UserId: Int)
过程如下:
listOfOldFormat -> groupby(shiftId, userId) -> sum(maximumValue-minimumValue) -> listOfNewFormat
答案 0 :(得分:2)
我们确实具有groupBy
函数,因此我们拥有所需的一切。
我不确定subtract the maximum value of each group from the minimum value of the same group and then sum the result
是什么意思(我应该总结什么?),所以我以group.value.max - group.value.min
的名字来做,而nozzeValue
是NewFormat
的意思。 / p>
代码段:
data class OldFormat(val shiftId: Int, val nozzleValue: Int, val nozzleId: Int, val userId: Int)
data class NewFormat(val shiftId: Int, val nozzleValue: Int, val userId: Int)
fun main() {
val old = listOf(
OldFormat(0, 10, 10, 0),
OldFormat(0, 120, 10, 1),
OldFormat(1, 11, 8, 10),
OldFormat(0, 10, 1, 1),
OldFormat(1, 50, 10, 10)
) // Example data
old.groupBy {
it.shiftId to it.userId // After it we have Map<Key, List<OldFormat>>, where key is pair of shiftId and userId
}.map { entry ->
val max = entry.value.maxBy { it.nozzleValue }?.nozzleValue ?: 0
val min = entry.value.minBy { it.nozzleValue }?.nozzleValue ?: 0
entry.key to (max - min) // Just do whatever you want with that data
}.map {
NewFormat(
shiftId = it.first.first,
userId = it.first.second,
nozzleValue = it.second
) // And now map it into type you want
}.let {
println(it) // Just for seeing result
}
}