How can merge multiple list to form alternative el...
# android
c
How can merge multiple list to form alternative elements ? We have kotlin zip function to combine two list and to form alternative element list , zip is limited for two list, I have to do for multiple list . what is best approach to do
t
If you'd like to zip N lists, you could use the
List
function:
Copy code
val firstList: List<A> = ...
val secondList: List<B> = ...
val thirdList: List<C> = ...
val mergedList: List<R> = List(
  minOf(firstList.size, secondList.size, thirdList.size)
) { index ->
  val a = firstList[index]
  val b = secondList[index]
  val c = thirdList[index]
  ... your combine logic ...
}
c
@Cicero @tseisel Thanks for showing your response to me I wrote it my own , it works like a charm
Copy code
private fun combine(lists: List<List<AmbientCardInfo>>): List<AmbientCardInfo> {

    if (lists.isEmpty()) return emptyList()

    val iteratorList = mutableListOf<Iterator<AmbientCardInfo>>()
    lists.forEach {
        iteratorList.add(it.iterator())
    }


    val combinedList = mutableListOf<AmbientCardInfo>()
    var index = 0


    while (iteratorList.size > 0) {
        val iteratorIndex = index % iteratorList.size
        when  {
            iteratorList[iteratorIndex].hasNext() -> {
                combinedList.add(iteratorList[iteratorIndex].next())
            }
            else -> {
                iteratorList.removeAt(iteratorIndex)
            }
        }
        index++
    }

    return combinedList
}
940 Views