How can I do a groupBy in my code by three or more fields? My code is like below:
val nozzleSaleReport = nozzleStateList.groupBy {
{it.shift.id},{it.createUser.id},{it.nozzle.id} // Here I need to add these three fields for grouping operation
}.map { entry ->
val max: Float = (entry.value.maxBy { it.nozzleState.finalLitreMechanical }?.nozzleState!!.finalLitreMechanical ?: 0).toString().toFloat()
val min: Float = (entry.value.minBy { it.nozzleState.finalLitreMechanical }?.nozzleState!!.finalLitreMechanical ?: 0).toString().toFloat()
NozzleSaleReport(entry.value[0].createUser.name, entry.value[0].shift.name, (max - min).toInt(),entry.value[0].shift.id, entry.value[0].nozzle.id, entry.value[0].nozzle.name)
}.let {
println(it)
}
The Kotlin standard library provides extension functions for grouping collection elements. The basic function groupBy () takes a lambda function and returns a Map. In this map, each key is the lambda result and the corresponding value is the List of elements on which this result is returned.
How groupBy works in Kotlin? The groupby function is one of the built-in functions to perform the grouping operations with the specific data that can be achieved using the customized filters even though it can be applied in the data.
sortedWith () is a function provided by the Kotlin library that returns a list of all the elements sorted by a specified comparator. According to official Kotlin documentation, the function definition is, sortedWith () takes a comparator as an argument and compares the custom properties of each object and sorts the same.
The basic function groupBy () takes a lambda function and returns a Map. In this map, each key is the lambda result and the corresponding value is the List of elements on which this result is returned. This function can be used, for example, to group a list of String s by their first letter.
Let's say the class of the elements of your collection is NozzleState
.
You want to group nozzle states by shift ID, create user ID and nozzle ID.
If I understand correctly, you thus want a different group for each distinct combination of shift ID, create user ID and nozzle ID.
So you need to create a class representing such a combination (let's name if Key
), and group the elements by their Key
:
data class Key(val shiftId: String, val createUserId: String, val nozzleId: String)
fun NozzleState.toKey() = Key(shift.id, createUser.id, nozzle.id)
nozzleStateList.groupBy { it.toKey() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With