If I have a list of objects with one of their prop...
# announcements
m
If I have a list of objects with one of their properties being type, how do I split them into sub groups such that they are bundled by their type property while also retaining the order?
s
list.groupBy { it.type }.values
t
@manlan in your example, the last “weekoff” is not grouped with the first item, so you mean only group adjacent items of the same type?
m
@Tibi Csabai Exactly!
@SackCastellon Thank you, but your suggestion misses the ordering part of the requirement 🙂
d
This was considered as a part of sliding window functions, but deemed too niche for the standard library. You probably just need to write a function to do it yourself.
😐 1
m
@diesieben07 I see. Thank you.
m
Copy code
items.fold(mutableListOf<MutableList<Item>>()) { acc, item ->
    acc.apply {
        when (lastOrNull()?.last()?.type) {
            item.type -> last().add(item)
            else -> add(mutableListOf(item))
        }
    }
}
however, I'm really sad that you can't destructure from the back of a list
m
@Michael de Kaste Wow! Thanks a ton! I could have never come up with something like this! 🤔
@Michael de Kaste You mean you can't do the same operation in the reverse order?
m
No I meant that my solution has
lastOrNull()?.last()?
and another
last()
with pattern matching or something else I could have maybe wrote acc as:
lists = (_*, lastList = (_*, lastItem))
to get:
Copy code
lists.apply{
    when(lastItem?.type){
        item.type -> lastList.add(item)
        else -> add(mutableListOf(item))
    }
}
which just reads better 🙂
but kotlin doesn't support that (yet)
m
Got it. Thanks for the response!