Under assumption that your list is sorted by date (should be, otherwise your code wouldn't make sense)
then some variation of groupBy/flatMap and similar functions can take up the mantle:
fun addChatHeaders(itemList: List<ChatMessage>): List<HelpCenterChatItem> {
return itemList.groupBy { it.date.dayOfYear }
.flatMap { (dayOfYear, messages) ->
listOf(HeaderDate(dayOfYear.toString())) + messages
}
}
I took a tiny shortcut to supply argument for HeaderDate, but this shouldn't be a problem. In fact, just grouping by
it.date
should be better (as it will handle cases when the list spans multiple years), and you can just pass that to formatter then.
And yes, groupBy keeps order of the keys in order it first encounters them, from docs:
The returned map preserves the entry iteration order of the keys produced from the original collection.