Justin
10/08/2019, 7:45 PMzip
, but instead of returning pairs based on index, it returns pairs based on a predicate.
For example:
data class A(val id: String)
data class B(val id: String)
val listA: List<A> = listOf(A(“3”), A(“8”))
val listB: List<B> = listOf(B(“8”), B(“2”), B(“4”))
val pairs: List<Pair<A, B>> = listA.someTransformation(listB) { it.id == id }
// ‘pairs’ would contain:
// listOf((A("8"), B("8"))
Would love to know if there’s a best practice around this type of operation?karelpeeters
10/08/2019, 7:47 PMJustin
10/08/2019, 7:50 PMB("3")
(matching the first element in listA)Jason
10/08/2019, 7:57 PMintersect
that takes a block for the equality test.Justin
10/08/2019, 8:01 PMkarelpeeters
10/08/2019, 8:04 PMlistA.flatMap { a -> listB.map { b -> a to b }.filter { (a, b) -> f(a,b) }
maybe with a asSequence()
inbetween.listA.flatMap { a -> listB.mapNotNull { b -> if (f(a,b)) a to b else null } }
Justin
10/08/2019, 8:05 PMf
in the first one (i.e. ... f(a,b) }
Jason
10/08/2019, 8:08 PMa.id == b.id
Justin
10/08/2019, 8:08 PMasSequence()
in between?Alowaniak
10/08/2019, 8:20 PMlistB.asSequence().map...
so that it doesn't actually create a B long list for each a
which gets mostly `filter`ed out after itJustin
10/08/2019, 8:36 PMJason
10/08/2019, 8:37 PM>>> listA.flatMap { a -> listB.map { b -> a to b }.filter { (a, b) -> a.id == b.id }}
res45: kotlin.collections.List<kotlin.Pair<Line_10.A, Line_9.B>> = [(A(id=8), B(id=8))]
Justin
10/08/2019, 8:42 PMJason
10/08/2019, 8:43 PM