S.P.
S.P.

Reputation: 2564

How can I join three list in one object in Kotlin

I'm trying to join three object list in one object with kotlin. But I don't know how to do it...

Some help will be appreciate.

This is my data class:

data class User(
    val address: Address,
    val company: Company,
    val email: String,
    val id: Int,
    val name: String,
    val phone: String,
    val username: String,
    val website: String
)

data class Post(
    val body: String,
    val id: Int,
    val title: String,
    val userId: Int
)

data class Comment(
    val body: String,
    val email: String,
    val id: Int,
    val name: String,
    val postId: Int
)

That I want to do is get one object like this if possible:

data class PostJoin(body: String, id: Int, title; String, user: User, comments: List<Comment>)

This is that I'm trying to do it, only can mix two objects but no how I want.

val postUsers = post.joinBy(users) { (post,user) -> post.userId == user.id }
                                    .map { PostViewModel(post = it.first, user = it.second) }

private inline fun <T : Any, U : Any> List<T>.joinBy(collection: List<U>, filter: (Pair<T, U>) -> Boolean): List<Pair<T, List<U>>> = map { t ->
        val filtered = collection.filter { filter(Pair(t, it)) }
        Pair(t, filtered)
    }

Upvotes: 0

Views: 456

Answers (1)

Quinn
Quinn

Reputation: 9404

Something like this might work:

val posts: List<Post> 
val users: List<User>
val comments: List<Comment>

// initialize lists
...

val joinedPosts = posts.fold(ArrayList<PostJoin>()) { joinedPosts, post ->
    val postComments = comments.filter { it.postId == post.id }
    val user = users.first { it.id == post.userId } 

    joinedPosts.add(PostJoin(post.body, post.id, post.title, user, postComments))
    joinedPosts
}

Seems to work for me: Try it online!. Though I did give a pretty lazy input.

Upvotes: 3

Related Questions