kotlin-过滤MutableList并将其他项追加到列表末尾

时间:2020-01-15 14:19:46

标签: android kotlin mutablelist

实际上,我想通过以下方式对列表进行排序: 我有一个这样的mutableList

noteList = mutableListOf<NoteDataHolder>().apply {
        notes.forEach {
            add(NoteDataHolder(it))
        }
}

想象NoteDataHolderId,我想按此Id排序我的列表

我的列表是这样的:[ {id=1}, {id=2}, {id=3}, {id=4} ]

当我这样过滤列表时:noteList.filter { it.note?.bookId == 4 }

我只收到[ {id=4} ]

最后,我想在item4之后获得所有物品,例如[ {id=4}, {id=1}, {id=2}, {id=3} ]

1 个答案:

答案 0 :(得分:3)

看起来您需要这样的东西:

fun reorderItems(input: List<NoteDataHolder>, predicate: (NoteDataHolder) -> Boolean): List<NoteDataHolder>{
    val matched = input.filter(predicate)
    val unmatched = input.filterNot(predicate)

    return matched + unmatched
}

使用:

noteList = reorderItems (noteList!!) {it.note?.bookId == 4}