Search code examples
androidkotlinmutablelist

kotlin - filter MutableList with append other items in the end of list


Actually I want to sort my list in this way: I have a mutableList like this

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

Imagin NoteDataHolder has Id and I want to sort my list by this Id

My list like this: [ {id=1}, {id=2}, {id=3}, {id=4} ]

when I filter my list like this:noteList.filter { it.note?.bookId == 4 }

I receive only [ {id=4} ]

finally, I want to get all item after item4 like this [ {id=4}, {id=1}, {id=2}, {id=3} ]


Solution

  • Looks like you need something like this:

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

    For use:

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