android - 如何在 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
}
似乎对我有用:在线尝试!. 虽然我确实给出了一个非常懒惰的输入。
推荐阅读
- java - 将数组的随机字母保存为字符串
- c++ - 分数而不是小数
- python - Intellisense 不提供 Python3 的可用方法或文档
- c++ - 如果给定值较低,则行和列之间的最大值 - c++
- c# - Xamarin.Forms ControlTemplate 不呈现背景
- laravel - REST API 中的 Laravel 5.3 OAuth 令牌错误
- testing - 在每次测试运行之前清除 Cursive REPL 状态
- postgresql - 在 pgadmin 中创建新的本地服务器?
- javascript - 列表在 x 轴上一直持续下去
- android - 在 Android 中管理库的依赖关系