What Java 8 Stream.collect equivalents are available in the standard Kotlin library?

问题:

In Java 8, there is Stream.collect which allows aggregations on collections.在 Java 8 中,有Stream.collect允许对集合进行聚合。 In Kotlin, this does not exist in the same way, other than maybe as a collection of extension functions in the stdlib.在 Kotlin 中,这不以相同的方式存在,除了可能作为 stdlib 中的扩展函数集合。 But it isn't clear what the equivalences are for different use cases.但尚不清楚不同用例的等效项是什么。

For example, at the top of the JavaDoc for Collectors are examples written for Java 8, and when porting them to Kolin you can't use the Java 8 classes when on a different JDK version, so likely they should be written differently.例如,在JavaDoc for Collectors顶部是为 Java 8 编写的示例,当将它们移植到 Kolin 时,您不能在不同的 JDK 版本上使用 Java 8 类,因此它们可能应该以不同的方式编写。

In terms of resources online showing examples of Kotlin collections, they are typically trivial and don't really compare to the same use cases.就展示 Kotlin 集合示例的在线资源而言,它们通常是微不足道的,并不能真正与相同的用例进行比较。 What are good examples that really match the cases such as documented for Java 8 Stream.collect ?什么是真正符合 Java 8 Stream.collect记录的案例的好例子? The list there is:那里的名单是:

  • Accumulate names into a List将名称累积到列表中
  • Accumulate names into a TreeSet将名称累积到 TreeSet 中
  • Convert elements to strings and concatenate them, separated by commas将元素转换为字符串并将它们连接起来,用逗号分隔
  • Compute sum of salaries of employee计算员工工资总额
  • Group employees by department按部门分组员工
  • Compute sum of salaries by department按部门计算工资总和
  • Partition students into passing and failing将学生分为合格和不合格

With details in the JavaDoc linked above.上面链接的 JavaDoc 中有详细信息。

Note: this question is intentionally written and answered by the author ( Self-Answered Questions ), so that the idiomatic answers to commonly asked Kotlin topics are present in SO.注意:这个问题是作者特意写的和回答的( 自我回答的问题),所以常见的 Kotlin 主题的惯用答案都在 SO 中。 Also to clarify some really old answers written for alphas of Kotlin that are not accurate for current-day Kotlin.还要澄清一些为 Kotlin alphas 编写的非常旧的答案,这些答案对于当前的 Kotlin 来说是不准确的。


解决方案:

参考一: https://en.stackoom.com/question/2LM22
参考二: https://stackoom.com/question/2LM22
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章