You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何将group为child的元素按order排序后加入ArrayList

解决方案

嘿,这问题很好解决!你已经搞定了筛选的核心逻辑,只需要在筛选后加上排序步骤就行。Kotlin的集合操作非常顺手,给你两种实现方式,按需选就行:

方式一:链式集合操作(更简洁)

直接把筛选和排序用链式调用完成,代码更紧凑易读:

// 先筛选group为CHILD的元素,再按question的order字段升序排序
myQuestionAnswers = data.results.questionAnswers
    .filter { it.question.group == CHILD }
    .sortedBy { it.question.order }

方式二:保留原循环逻辑(适合需要额外操作的场景)

如果你想保留原来的循环遍历方式(比如遍历过程中还要做其他处理),可以在筛选完成后对列表进行排序:

// 原筛选逻辑不变
for (element in data.results.questionAnswers) {
    if (element.question.group == CHILD) {
        myQuestionAnswers.add(element)
    }
}
// 筛选完成后,按question.order升序排序
myQuestionAnswers.sortBy { it.question.order }

逻辑说明

  • filter函数和你原来的循环作用一致,只保留group等于CHILD的元素;
  • sortedBy(或者sortBy)会根据指定的question.order字段对集合做升序排序,刚好满足你order1在第一个位置、order2在第二个位置的要求。

对应你给出的JSON示例,最终排序后的列表顺序会是:

  • order=1的question(id:2082411987)
  • order=2的question(id:142373470)
  • order=3的question(id:1155092697)

完全符合你的需求~

内容的提问来源于stack exchange,提问作者Miss. Ellen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:25:27