How to transform three lists based on userId in a single object, where each object has the respected list object as a variable.
data class User(val id: String)
data class Book(val id: String, val userId: String)
data class Order(val id: String, val userId: String)
Input
val users: List<User> = listOf(
User(id = "u1"),
User(id = "u2"),
User(id = "u3")
)
val books: List<Book> = listOf(
Book(id = "b1.u1", userId = "u1"),
Book(id = "b2.u1", userId = "u1"),
Book(id = "b3.u2", userId = "u2"),
Book(id = "b4.ux", userId = "ux")
)
val order: List<Order> = listOf(
Order(id = "o1", userId = "u1"),
Order(id = "o2", userId = "u1"),
Order(id = "03", userId = "u2"),
Order(id = "o4", userId = "u1")
)
Output
val result = listOf(Result(user, book, order))
CodePudding user response:
Hard to get exactly what you need as output. To me, it makes the most sense to get a list of books and orders for each user. If that is the case, then you can do this:
data class Result(val user: User, val books: List<Book>, val orders: List<Order>)
val results = users.map { user ->
val userBooks = books.filter { it.userId == user.id }
val userOrders = orders.filter { it.userId == user.id }
Result(user, userBooks, userOrders)
}
CodePudding user response:
For same size lists.
val newList = users.indices.forEach { index ->
Result(users[index], books[index], order[index])
}