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

后端 未结 4 1793
礼貌的吻别
礼貌的吻别 2020-11-27 09:05

In Java 8, there is Stream.collect which allows aggregations on collections. In Kotlin, this does not exist in the same way, other than maybe as a collection of extension f

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 09:29

    There are some cases where it is hard to avoid calling collect(Collectors.toList()) or similar. In those cases, you can more quickly change to a Kotlin equivalent using extension functions such as:

    fun  Stream.toList(): List = this.collect(Collectors.toList())
    fun  Stream.asSequence(): Sequence = this.iterator().asSequence()
    

    Then you can simply stream.toList() or stream.asSequence() to move back into the Kotlin API. A case such as Files.list(path) forces you into a Stream when you may not want it, and these extensions can help you to shift back into the standard collections and Kotlin API.

提交回复
热议问题