1

I have class CatalogProduct(id: String, name: String) to declare a product

I have two list below:

val newestCatalogProductList = mutableListOf<CatalogProduct>()
newestCatalogProductList.add(CatalogProduct("A1", "Apple"))
newestCatalogProductList.add(CatalogProduct("A2", "Banana"))
newestCatalogProductList.add(CatalogProduct("A3", "Orange"))
newestCatalogProductList.add(CatalogProduct("A4", "Pineapple"))

val popularCatalogProductList = mutableListOf<CatalogProduct>()
popularCatalogProductList.add(CatalogProduct("A5", "Milk"))
popularCatalogProductList.add(CatalogProduct("A6", "Sugar"))
popularCatalogProductList.add(CatalogProduct("A7", "Salt"))
popularCatalogProductList.add(CatalogProduct("A8", "Sand"))

I merged two list successfully by code below:

newestCatalogProductList.union(popularCatalogProductList)

But, i can not ordering interleaved merged list as expect:

CatalogProduct("A1", "Apple")
CatalogProduct("A5", "Milk")
CatalogProduct("A2", "Banana")
CatalogProduct("A6", "Sugar")
CatalogProduct("A3", "Orange")
CatalogProduct("A7", "Salt")
CatalogProduct("A4", "Pineapple")
CatalogProduct("A8", "Sand")

I'm begin study Kotlin. Please help me if you can explain or make example or give me reference link. So I thank you.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • Create a new empty mutable list. Loop from 0 to the size of lists (assuming they have the same size). For each index, add to the new list the element from the two lists at that index. – JB Nizet Nov 22 '19 at 19:27

1 Answers1

2

You can zip the lists to pair up items with the same index as lists of two items, and then flatten them:

val interleaved = newestCatalogProductList.zip(popularCatalogProductList) { a, b -> listOf(a, b) }
    .flatten()

If one of the lists might be longer you probably want to keep the remaining items of the longer list. In that case you might manually zip the items this way:

val interleaved2 = mutableListOf<CatalogProduct>()
val first = newestCatalogProductList.iterator()
val second = popularCatalogProductList.iterator()
while (interleaved2.size < newestCatalogProductList.size + popularCatalogProductList.size){
    if (first.hasNext()) interleaved2.add(first.next())
    if (second.hasNext()) interleaved2.add(second.next())
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154