listkotlincollectionsmutablelist

Extract list from a list in Kotlin based on object


I am trying to parse a list of data object define by:

data class BookInfo(
        val id: Int?,
        val description: String)

I receive a list of this BookInfo which could be up to 50.

I am trying to regroup the list of book by id and then run a forEach on each list of regrouped BookInfo by id

Something like:

val tmpList: List = [BookInfo(1, "test"), BookInfo(2, "tit"),BookInfo(1, "tkllt"),BookInfo(3, "test"),BookInfo(1, "test"),BookInfo(2, "test"),BookInfo(3, "test"),BookInfo(2, "test")]

then using a tmpList.<function_in_kotlin_condition_on_id>.forEach() will run a forEach and the result is a subList of BookInfo with the same id.

It's like extracting a list using .filter to get a sublist of all BookInfo having the same id and then runing a forEach on all various id

tmpList.<extract_by_id>.forEach { sublist .... and the sublist will be

BookInfo(1, "test"), BookInfo(1, "tkllt"), BookInfo(1, "test"), next loop on the forEach will be BookInfo(2, "tit"),BookInfo(2, "test"),BookInfo(2, "test") and finally BookInfo(3, "test"),BookInfo(3, "test"),

I know it's seems strangely explained

Any idea, how to do it


Solution

  • You can do groupBy and then take the values of the resulting map. Example:

    fun main() {
    
        val books = arrayOf(
            BookInfo(1,"a"),
            BookInfo(2,"b"),
            BookInfo(1,"c"),
            BookInfo(2,"d"),
            BookInfo(1,"e"),
            BookInfo(3,"f")
        )
    
        books.groupBy { it.id }.values.forEach {
            println(it)
        }
    
    }
    
    data class BookInfo(
        val id: Int?,
        val description: String)
    

    Output:

    [BookInfo(id=1, description=a), BookInfo(id=1, description=c), BookInfo(id=1, description=e)]
    [BookInfo(id=2, description=b), BookInfo(id=2, description=d)]
    [BookInfo(id=3, description=f)]