myanmarking
10/21/2021, 3:22 PMfun addChatHeaders(itemList: List<ChatMessage>): List<HelpCenterChatItem> {
return buildList {
itemList.forEachIndexed { index, item ->
val current: ChatMessage = item
val previous: ChatMessage? = itemList.getOrNull(index - 1)
if (previous == null || (previous.date.dayOfYear != current.date.dayOfYear)) {
add(
HelpCenterChatItem.HeaderDate(
dateFormatter.format(
current.date,
DatePattern.ISO_DAY_MONTH_YEAR_SLASHED
)
)
)
}
add(current)
}
}
}
Paul Griffith
10/21/2021, 3:44 PMzipWithNext
for this? https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/zip-with-next.htmlKlitos Kyriacou
10/21/2021, 5:01 PMPaul Griffith
10/21/2021, 5:02 PMOrhan Tozan
10/21/2021, 6:33 PMOrhan Tozan
10/21/2021, 6:33 PMRoukanken
10/21/2021, 7:21 PMfun 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.
ephemient
10/22/2021, 3:38 AMmyanmarking
10/22/2021, 11:24 AM