鉴于我有两个列表:
val ints = listOf(0, 1, 2)
val strings = listOf("a", "b", "c")
Run Code Online (Sandbox Code Playgroud)
我想要所有可能的元素组合
0a, 1a, 2a, 0b 等等
是否有比以下更优雅的方式:
ints.forEach { int ->
strings.forEach { string ->
println("$int $string")
}
}
Run Code Online (Sandbox Code Playgroud)
dni*_*Hze 10
您可以根据flatMapstdlib函数编写这些扩展函数:
// Extensions
fun <T, S> Collection<T>.cartesianProduct(other: Iterable<S>): List<Pair<T, S>> {
return cartesianProduct(other, { first, second -> first to second })
}
fun <T, S, V> Collection<T>.cartesianProduct(other: Iterable<S>, transformer: (first: T, second: S) -> V): List<V> {
return this.flatMap { first -> other.map { second -> transformer.invoke(first, second) } }
}
// Example
fun main(args: Array<String>) {
val ints = listOf(0, 1, 2)
val strings = listOf("a", "b", "c")
// So you could use extension with creating custom transformer
strings.cartesianProduct(ints) { string, int ->
"$int $string"
}.forEach(::println)
// Or use more generic one
strings.cartesianProduct(ints)
.map { (string, int) ->
"$int $string"
}
.forEach(::println)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
957 次 |
| 最近记录: |