Home > other >  How to map list of list items to index in HorizontalPager?
How to map list of list items to index in HorizontalPager?

Time:08-18

I have a List

val listOfList: List<SublistObject> = emptyList()

, which in turn consists again of sub lists:

@Serializable
data class SublistObject(
    val id: Int = 0,
    val pages: List<HorizontalScrollerPage> = emptyList()
)

The pages in SublistObject might have different size. E.g. we have a list of SublistObject, where as the first SublistObject has 3 pages. The second SublistObject has 2 pages. And the third SublistObject has 3 pages :

  1. SublistObject : * * *
  2. SublistObject : * *
  3. SublistObject : * * *

So we would have 3 lists with 8 items in total. I would like to traverse them like:

1.1 -> 1.2 -> 1.3 -> 2.1 -> 2.2 -> 3.1 -> 3.2 -> 3.3

what I do like:

listOfLists.forEach{ subList ->
    subList.forEach{ item ->
        print(item)
    }
}

But I would like to show each element in an

HorizontalPager(count = totalPagesCount){ index ->
   val item = listOfLists.get(index)
}
  1. How can I calculate the amount of all items easily (without two forEachs)?
  2. How can I map e.g. index 4 to 2.2 ? Or how to use flatMap or flatMapIndexed() here?

CodePudding user response:

You could create a separate list for this:

val flatList = listOfLists.flatten()

And then all elements will be there as you expect, and you can query the .size and ask for a specific index with flatList[index].

CodePudding user response:

Its simple. Here it would return list of pages where it will take all pages from each items and does the transformation.

var flattenedMap = listOfLists.flatMap{it.pages}

I have just replicated your scenario with simple code. Hope it will work for you.

data class SublistObject(
    val id: Int = 0,
    val pages: List<HorizontalScrollerPage> = emptyList()
){
    override fun toString(): String {
        return "Id:$id -- ${pages.joinToString(",")}\n"
    }
}

class HorizontalScrollerPage(var pageNo: Int = Random.nextInt(100)){
    override fun toString(): String {
        return "PageNo: $pageNo"
    }
}


    val listOfList: ArrayList<SublistObject> = arrayListOf()
    listOfList.add(
        SublistObject(
            id = 1,
            pages = arrayListOf(HorizontalScrollerPage(), HorizontalScrollerPage(), HorizontalScrollerPage())
        )
    )
    listOfList.add(
        SublistObject(
            id = 2,
            pages = arrayListOf(HorizontalScrollerPage(), HorizontalScrollerPage(), HorizontalScrollerPage())
        )
    )
    println("---Separate List: ---")
    println(listOfList.joinToString(""))
    println("---Flattened List: ---")
val flattenedList :List<HorizontalScrollerPage> = listOfList.flatMap { it.pages }
println(flattenedList)

enter image description here

  • Related