I tried to recreate your code inside main method. But first I had to convert ProductStore(), Product(), StorageType() and QuantityType() normal Kotlin Classes to Data Classes in order to easily print them as a String using the implicit toString().
I then made an example of the Stock Data Class as follows:
fun main() {
//instance of the Stock Class
val stock = Stock(
product = arrayListOf(
ProductStore(
storage_type = StorageType(libellus = "frozen"),
quantity = 13.0,
expiration_date = "",
product = Product(),
quantity_type = QuantityType()
), ProductStore(
storage_type = StorageType(libellus = "fresh"),
quantity = 18.0,
expiration_date = "",
product = Product(),
quantity_type = QuantityType()
), ......}}
From here I just used @broot approach to group the ArrayList of ProductStore elements into a Map Object:
//grouping the stock
val productsGroups = stock.product.groupBy { productStore ->
when (productStore.storage_type?.libellus) {
"frozen" -> {
"frozen"
}
"fresh" -> {
"fresh"
}
else -> {
"ambient"
}
}
}
println(productsGroups)
}
The output of println(productsGroups) was a printed Map Object whereby the Stock's StorageType (frozen, ambient, fresh) was keys and corresponding lists as the values.
{frozen=[ProductStore(quantity=13.0, expiration_date=, product=Product(id=null, name=null, image=null), storage_type=StorageType(id=null, libellus=frozen), quantity_type=QuantityType(libellus=null))],
fresh=[ProductStore(quantity=18.0, expiration_date=, product=Product(id=null, name=null, image=null), storage_type=StorageType(id=null, libellus=fresh), quantity_type=QuantityType(libellus=null))],
ambient=[ProductStore(quantity=2021.0, expiration_date=, product=Product(id=null, name=null, image=null), storage_type=StorageType(id=null, libellus=ambient), quantity_type=QuantityType(libellus=null))]}