How to perform action for all combinations of elements in lists?
The name of the output you're looking for is a Cartesian Product.
If you don't need all of the combinations up front, and you're just searching for one or more, you could make it a lazily generated sequence:
private fun <A, B> lazyCartesianProduct(
listA: Iterable<A>,
listB: Iterable<B>
): Sequence<Pair<A, B>> =
sequence {
listA.forEach { a ->
listB.forEach { b ->
yield(a to b)
}
}
}
Then you can map, filter etc only what you need:
val names = listOf("John", "Tom")
val days = listOf(1, 2, 3)
lazyCartesianProduct(names, days)
.map { it.toSomethingElse() }
.find { it.isWhatImLookingFor() }
The forEach
is the closest as it can get:
names.forEach {
i -> days.forEach { j -> f(i, j)}
}
Example:
private fun f(i: String, j: Int) = println("$i,$j")
Result:
John,1
John,2
John,3
Tom,1
Tom,2
Tom,3
What's wrong with a regular for
loop?
for (name in names) for (day in days) f(name, day)