根据 Kotlin 中的对象参数从一个对象列表创建多个对象列表

发布于 2025-01-19 08:19:13 字数 549 浏览 3 评论 0原文

属性的对象列表,如以下:

列表
ID:1
ID:1 ID:2
ID:2
ID:2
ID:3

我想基于该属性创建不同的

列表我有一个带有int, C
ID:1ID:2 ID:3
ID:1ID:2

我找到了一些方法,但我想知道是否有有效的方法,也许使用Kotlin已经提供的某种方法。

I Have a list of object with an Int attribute, like this:

List
id: 1
id: 1
id: 2
id: 2
id: 3

and i want to create different list based on that attribute, like this:

List AList BList C
id: 1id: 2id: 3
id: 1id: 2

i found some ways to do it but i wanted to know if there was an efficient way, maybe using some method that kotlin already provide.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

格子衫的從容 2025-01-26 08:19:13
data class Test(
  val id: Int,
  val text: String
)

val list = listOf(
  Test(1, "a"),
  Test(1, "b"),
  Test(2, "c"),
  Test(2, "d"),
  Test(3, "e")
)

val result = list
  .groupBy { test -> test.id }
  .map { it.value }

result.forEach(::println)

输出:

[Test(id=1, text=a), Test(id=1, text=b)]
[Test(id=2, text=c), Test(id=2, text=d)]
[Test(id=3, text=e)]
data class Test(
  val id: Int,
  val text: String
)

val list = listOf(
  Test(1, "a"),
  Test(1, "b"),
  Test(2, "c"),
  Test(2, "d"),
  Test(3, "e")
)

val result = list
  .groupBy { test -> test.id }
  .map { it.value }

result.forEach(::println)

Output:

[Test(id=1, text=a), Test(id=1, text=b)]
[Test(id=2, text=c), Test(id=2, text=d)]
[Test(id=3, text=e)]
东走西顾 2025-01-26 08:19:13

您想要的是GroupBy:

​。

What you want is the groupBy: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/group-by.html

It will return a map, that the key is the property value that you used to group by, and the value is the list.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文