本文介绍了什么是Java Stream.collect的Kotlin等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想收集我的Kotlin集合到一个没有内置到stdlib的东西,我该怎么做?

If I want to collect my Kotlin collection into something that isn't built into the stdlib, how do I do it?

推荐答案

对于不是由内置操作覆盖的方案 toList()等,你可以使用事实,collect只是一个折叠。所以给定

For scenarios not covered by built in operations toList() etc, you can use the fact that collect is just a fold. So given

val list: List<Pair<String, Int>> = listOf("Ann" to 19, "John" to  23)
val map: Map<String, Int> = list.fold(HashMap(), { accumulator, item ->
    accumulator.put(item.first, item.second); accumulator})

如果您随后定义扩展函数

If you then define an extension function

fun <T, R> Iterable<T>.collectTo(accumulator: R, accumulation: (R, T) -> Unit) =
    this.fold(accumulator, { accumulator, item -> accumulation(accumulator, item); accumulator } )

您可以进一步简化

val map2: Map<String, Int> = list.collectTo(HashMap(), { accumulator, item ->
    accumulator.put(item.first, item.second) })

虽然在这种情况下,你可以使用 .toMap 扩展函数。

Although in this case of course you could just use the .toMap extension function.

这篇关于什么是Java Stream.collect的Kotlin等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 00:05
查看更多