两个列表的所有可能的组合
鉴于我有两个名单:
val ints = listOf(0, 1, 2) val strings = listOf("a", "b", "c")
我想要所有可能的元素组合
0a, 1a, 2a, 0b
等
有没有更优雅的方式比:
ints.forEach { int -> strings.forEach { string -> println("$int $string") } }
你可以根据flatMap
stdlib函数编写这些扩展函数:
// Extensions fun Collection.cartesianProduct(other: Iterable): List> { return cartesianProduct(other, { first, second -> first to second }) } fun Collection.cartesianProduct(other: Iterable, transformer: (first: T, second: S) -> V): List { return this.flatMap { first -> other.map { second -> transformer.invoke(first, second) } } } // Example fun main(args: Array) { 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) }