Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin; group by multiple fields

Tags:

kotlin

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)
}
like image 521
amin mohammadi Avatar asked Mar 07 '19 10:03

amin mohammadi


People also ask

How to group collection elements in Kotlin?

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.

What is groupby in Kotlin and how it works?

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.

What is sortedwith () function in Kotlin?

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.

How do you group a list of elements in Python?

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.


1 Answers

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() }
like image 78
JB Nizet Avatar answered Nov 16 '22 15:11

JB Nizet