Kotlin开发:如何按类指定属性对ProductStore的ArrayList分组或排序
Kotlin实现ProductStore列表的排序与分组
按StorageType的libellus字段排序
Kotlin标准库提供了专用的集合排序扩展方法,可直接调用,注意要处理storage_type和libellus两个可空字段的空值场景:
// 1. 升序排序,返回新的不可变列表,空值默认排在最前面 val sortedList = productList.sortedBy { it.storage_type?.libellus } // 2. 升序排序,空值排在末尾 val sortedListNullLast = productList.sortedBy { it.storage_type?.libellus ?: Char.MAX_VALUE.toString() } // 3. 降序排序 val sortedDescList = productList.sortedByDescending { it.storage_type?.libellus } // 4. 直接修改原ArrayList,不需要生成新列表,用sortBy productList.sortBy { it.storage_type?.libellus }
按libellus相同值分组
使用groupBy扩展方法即可实现分组,返回值为Map<String?, List<ProductStore>>,键为libellus的值,空值也会作为独立的分组存在:
// 基础分组,保留libellus为null的分组 val groupedMap = productList.groupBy { it.storage_type?.libellus } // 过滤掉libellus为null的分组 val filteredGroupedMap = productList .filter { it.storage_type?.libellus != null } .groupBy { it.storage_type!!.libellus } // 遍历分组使用示例 groupedMap.forEach { (libellusValue, productGroup) -> // libellusValue为当前分组的标识,productGroup为当前分组下的所有ProductStore实例 }
内容的提问来源于stack exchange,提问作者dja
相关产品推荐
相关产品推荐

