如何在Kotlin中将List<Example>按date字段转为排序后的List<List<Example>>
解决方案
要实现将List<Example>转换为按date分组且外层列表按date排序的List<List<Example>>,可以结合Kotlin的groupBy、sorted和map函数完成,具体实现如下:
1. 基础实现(按date分组+外层列表按date排序)
先按date字段对原始列表分组,再对分组的date键排序,最后映射为目标嵌套列表结构:
data class Example(val date: String, val color: Int, val startTime: String) // 示例原始列表 val list: List<Example> = listOf( Example("2024-05-02", 1, "09:00"), Example("2024-05-01", 2, "10:00"), Example("2024-05-02", 3, "08:30") ) // 按date分组,得到键为date、值为对应Example列表的Map val groupedByDate = list.groupBy { it.date } // 对date键排序,再映射为最终的嵌套列表 val result: List<List<Example>> = groupedByDate.keys .sorted() // 若date是yyyy-MM-dd格式,字符串自然排序即可 .map { groupedByDate[it]!! } // 分组键必然存在,使用!!安全
执行后result的结构为:
[ [Example(date=2024-05-01, color=2, startTime=10:00)], [Example(date=2024-05-02, color=1, startTime=09:00), Example(date=2024-05-02, color=3, startTime=08:30)] ]
2. 进阶:内层列表按startTime排序
如果需要每个分组内的元素按startTime进一步排序,只需在map时对分组列表额外调用sortedBy:
val resultWithInnerSort: List<List<Example>> = groupedByDate.keys .sorted() .map { groupedByDate[it]!!.sortedBy { example -> example.startTime } }
此时内层列表会按startTime升序排列:
[ [Example(date=2024-05-01, color=2, startTime=10:00)], [Example(date=2024-05-02, color=3, startTime=08:30), Example(date=2024-05-02, color=1, startTime=09:00)] ]
3. 处理非标准日期格式
如果date格式不是yyyy-MM-dd(比如MM/dd/yyyy),字符串自然排序会出错,需要借助日期解析工具自定义排序逻辑:
import java.time.LocalDate import java.time.format.DateTimeFormatter val dateFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy") // 按实际日期排序date键 val sortedDates = groupedByDate.keys .sortedWith(compareBy { LocalDate.parse(it, dateFormatter) }) val resultWithCustomDateSort = sortedDates.map { groupedByDate[it]!! }
内容的提问来源于stack exchange,提问作者Jekis Osipov
相关产品推荐
相关产品推荐

