繁体   English   中英

如何在 Kotlin 的一个对象中加入三个列表

[英]How can I join three list in one object in Kotlin

我正在尝试使用 kotlin 将三个对象列表加入一个对象中。 但我不知道该怎么做...

一些帮助将不胜感激。

这是我的数据类:

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
)

如果可能的话,我想做的是得到一个这样的对象:

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

这是我正在尝试做的,只能混合两个对象,但不是我想要的。

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

这样的事情可能会起作用:

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
}

似乎对我有用: 在线尝试! . 尽管我确实提供了一个非常懒惰的输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM