Sharan
Sharan

Reputation: 1275

How to join three lists into a single Object

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))

Upvotes: 1

Views: 101

Answers (2)

Arpit Shukla
Arpit Shukla

Reputation: 10493

You can group the books and orders by userId and then for each user you can pick the corresponding books and orders.

val booksMap = books.groupBy { it.userId }
val ordersMap = orders.groupBy { it.userId }
users.map {
    Result(
        user = it,
        books = booksMap[it.id] ?: emptyList(),
        orders = ordersMap[it.id] ?: emptyList()
    )
}

Here Result is:

data class Result(val user: User, val books: List<Book>, val orders: List<Order>)

Upvotes: 2

marstran
marstran

Reputation: 27971

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)
}

Upvotes: 1

Related Questions