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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章