我有一个nozzleState对象列表,这些对象按nozzleStateDate排序。数据类如下所示
data class NozzleState(val shiftId: Int, val nozzleValue: Int, val nozzleId: Int, val userId: Int, nozzleStateDate: String)
我需要从前一个对象的nozzleValue中减去最新的对象的nozzleStateObject,我现在有了这段代码,但是我不知道下一步该做什么:
val nozzleSaleReport = nozzleStateList
.sortedByDescending { item-> item.nozzleStateDate }.groupBy {
it.nozzleId}
换句话说,如果有
(10, 8, 6, 3)
对于列表中的nozzleValue字段,结果是
(10-8, 8-6, 6-3, 3-0)
发布于 2019-03-07 13:07:27
在这种情况下,nozzleSaleReport
没有帮助。
如果nozzleStateList
已经按nozzleStateDate
升序排序,那么您需要:
val dif = nozzleSortedList.last().nozzleValue - nozzleSortedList[nozzleSortedList.size - 2].nozzleValue
如果没有对nozzleStateList
进行排序,那么首先需要对其排序,降序
val nozzleSortedList= nozzleStateList.sortedByDescending { it.nozzleStateDate }
val dif = nozzleSortedList[0].nozzleValue - nozzleSortedList[1].nozzleValue
无论如何,您必须检查列表的大小是否至少为2。
另外,由于nozzleStateDate
是一个String
,所以它必须采用适当的格式,
就像yyyy-MM-dd
一样,所以它是可比较的,排序将是正确的。
编辑
要将减法应用于列表中的所有项,您可以这样做:
nozzleStateList.forEachIndexed { index, item ->
if (index < nozzleStateList.size - 1)
item.nozzleValue -= nozzleSortedList[index + 1].nozzleValue
}
但是,您必须将数据类中nozzleValue
的定义从val
更改为var
。
https://stackoverflow.com/questions/55043296
复制相似问题