【问题标题】:functionally combine list of same object在功能上组合相同对象的列表
【发布时间】:2021-12-21 15:59:17
【问题描述】:

我有一组需要合并和输出的警报。我正在努力了解如何在功能上做到这一点。我有我需要的一切,我只想将格式和输出结合起来。

orderedStatuses 包含一组警报

data class Alert(
    val status: String,
    val recordId: String
)

这是我目前正在返回的内容

  Alerts:
        Status1 : 
          000000000000
        Status1 : 
          111111111111
        Status2 : 
         222222222222
        Status2 : 
         333333333333
        Status3 : 
         444444444444
        Status3 : 
          555555555555

这就是我想要的:

Alerts:
    status1 : 
    ('00000', '111111')
    status2 : 
    ('222222', '333333')
    status3 : 
    ('444444', '55555')

当前代码:

val alert = if (orderedStatuses.isEmpty()) {
    "No alerts found for status"
} else {
    "Records:\n" + orderedStatuses.joinToString("\n") { it ->
        "\t${it.status} : \n" + it.recordId

    }
}

【问题讨论】:

  • 您能否详细说明输出中的('00000', '111111') 是什么?应该是recordId
  • 是的,你是对的@viv3k
  • val recordIdsByStatus: Map<String, List<String>> = orderedStatuses.groupBy(Alert::status).mapValues { (_, alerts) -> alerts.map(Alert::recordId) }
  • 你的问题有点不清楚。您可以添加orderedStatuses 的值吗?做出非常粗略的假设,这就是你要找的pl.kotl.in/VSuhOLGMP 吗?

标签: java kotlin functional-programming set


【解决方案1】:
data class Alert(
  val status: String,
  val recordId: String
)

val alerts = listOf(
  Alert("Status1", "00000"),
  Alert("Status1", "111111"),
  Alert("Status2", "222222"),
  Alert("Status2", "333333"),
  Alert("Status3", "444444"),
  Alert("Status3", "55555")
)

alerts
  .groupBy { it.status }
  .map { map -> map.key + " : \n('" + map.value.joinToString("', '") { it.recordId } + "')\n" }
  .forEach { print(it) }

这将打印:

Status1 : 
('00000', '111111')
Status2 : 
('222222', '333333')
Status3 : 
('444444', '55555')

这可能更具可读性:

alerts
  .groupBy(Alert::status)
  .map { (key, value) -> 
    key + " : \n('" + value.joinToString("', '", transform = Alert::recordId) + "')\n"
  }
  .forEach(::print)

Detailed example on Kotlin Playground

【讨论】:

  • 这行得通,但您能否详细介绍一下您编写的 .Map 中发生的事情。
  • @AnthonyEdwardsStan groupBy 返回Map,其中键是您分组的元素(状态),值是每个组中的项目(List)。可能令人困惑的是,这之后是一个map 调用,它转换集合中的每个元素(即每个Map.Entry),而lukas 调用转换函数中的每个条目map。想象一下它在函数中被称为group
  • @AnthonyEdwardsStan 在 Kotlin Playground 上添加了一个详细示例(请参阅我的答案底部的链接),其中显示了所有用作显式函数的 lambda。
猜你喜欢
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多