Home > Back-end >  create objects based on elements of a list
create objects based on elements of a list

Time:06-22

Suppose I have the below lists and data classes in Kotlin:

val qrtr = listOf("Q1", "Q2", "Q3", "Q4")

data class X(val name: String, val location: String)
val x1 = X("John Doe", "USA")
val x2 = X("Jane Doe", "Singapore")
val allX = listOf(x1, x2)

data class Y(val title: String, val rating: Double)
val y1 = Y("Senior", 4.8)
val y2 = Y("Junior", 4.5)
val allY = listOf(y1, y2)

Is there an easy way to create another list using a 3rd data class using the above lists of allX, allY and qrtr.

data class Z(val x: X, val y: Y, quarter: String)

For the above data class (Z), I would like to merge details of allX and allY by its index position..and have this data repeated for each element in qrtr.

If it were to be done manually, it would look like this: But I'd like it done programmatically.

val z1 = Z(x1, y1, "Q1")
val z2 = Z(x1, y1, "Q2")
val z3 = Z(x1, y1, "Q3")
val z4 = Z(x1, y1, "Q4")
val z5 = Z(x2, y2, "Q1")
val z6 = Z(x2, y2, "Q2")
val z7 = Z(x2, y2, "Q3")
val z8 = Z(x2, y2, "Q4")
val allZ = listOf(z1, z2, z3, z4, z5, z6, z7, z8)

CodePudding user response:

val result = allX.zip(allY).flatMap { (x, y) -> qrtr.map { q -> Z(x, y, q) } }

CodePudding user response:

You can do this:

val allZ = allX.flatMapIndexed { index, x -> qrtr.map { q -> Z(x, allY[index], q) } }
allZ.forEach {
    println(it)
}

Output:

Z(x=X(name=John Doe, location=USA), y=Y(title=Senior, rating=4.8), quarter=Q1)
Z(x=X(name=John Doe, location=USA), y=Y(title=Senior, rating=4.8), quarter=Q2)
Z(x=X(name=John Doe, location=USA), y=Y(title=Senior, rating=4.8), quarter=Q3)
Z(x=X(name=John Doe, location=USA), y=Y(title=Senior, rating=4.8), quarter=Q4)
Z(x=X(name=Jane Doe, location=Singapore), y=Y(title=Junior, rating=4.5), quarter=Q1)
Z(x=X(name=Jane Doe, location=Singapore), y=Y(title=Junior, rating=4.5), quarter=Q2)
Z(x=X(name=Jane Doe, location=Singapore), y=Y(title=Junior, rating=4.5), quarter=Q3)
Z(x=X(name=Jane Doe, location=Singapore), y=Y(title=Junior, rating=4.5), quarter=Q4)

Note that it will crash though if allX has more elements than allY

  • Related