kotlin数据表结构,用于保存和排序数据



我用这个结构来保存数据它将为kotlin/js表提供数据

data class TableData<T : Any>(
var items: List<T>,
var fieldList: MutableList<KProperty1<T, Comparable<*>>> = mutableListOf(),
) : Iterable<T> {
override fun iterator() = items.iterator()
fun handleSortRequest(incoming: KProperty1<T, Comparable<*>>) {
fieldList.add(incoming)
fieldList.reverse()
items = items.sortedWith(compareBy(*fieldList.toTypedArray()))
}
}

它工作得很好,我可以通过像

这样的东西对每一列进行排序
sort(Meal::calories)

我想通过在列中添加箭头来扩展它,以便像许多流行的数据表一样升序和降序,这是可能的吗?我该怎么做呢?

我的测试类是

data class Meal(
val calories: Int,
val salad: String,
val mainCourse: String,
val desert: String,
)

,我用这张餐单喂桌子。

val mealList = listOf(
Meal(calories = 90, salad = "Fruit Salad", mainCourse = "Pork", desert = "cookies"),
Meal(calories = 10, salad = "Shrimp Salad", mainCourse = "Burgers", desert = "cookies"),
Meal(calories = 30, salad = "Tuna Salad", mainCourse = "Chicken", desert = "pie"),
Meal(calories = 40, salad = "Cobb Salad", mainCourse = "Steak", desert = "jello"),
Meal(calories = 40, salad = "Caesar Salad", mainCourse = "Salmon", desert = "pudding"),
Meal(calories = 40, salad = "Potato Salad", mainCourse = "Hot Dogs", desert = "cake"),
Meal(calories = 20, salad = "Garden Salad", mainCourse = "Eggs", desert = "ice cream"),
)

显然,您需要向handleSortRequest方法传递另一个参数,指定排序方向。此外,您需要更改fieldList中存储的项的类型,以便与排序方向一起存储选择器。

现在,可以根据这些数据构建比较器:

data class TableData<T : Any>(
var items: List<T>,
var fieldList: MutableList<Pair<KProperty1<T, Comparable<*>>, Boolean>> = mutableListOf(),
) : Iterable<T> {
override fun iterator() = items.iterator()
fun handleSortRequest(incoming: KProperty1<T, Comparable<*>>, isAscending: Boolean = true) {
fieldList.add(incoming to isAscending)
fieldList.reverse()

val comparator = fieldList
.map { (selector, isAsc) -> if (isAsc) compareBy(selector) else compareByDescending(selector) }
.reduce { acc, x -> acc.thenComparing(x) }
items = items.sortedWith(comparator)
}
}

相关内容

  • 没有找到相关文章

最新更新