Issue
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)
Solution
val result = allX.zip(allY).flatMap { (x, y) -> qrtr.map { q -> Z(x, y, q) } }
Answered By - lukas.j
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.