I have two lists: listA = listOf<ObjA>(…..) ...
# getting-started
d
I have two lists: listA = listOf<ObjA>(…..) listB = listOf<ObjB>(…..) ObjA and ObjB have a common field called “fieldC” how can filter listA, so that it removes any ObjA object whose “fieldC” is not present in any element of listB?
d
is this what you need? https://pl.kotl.in/EK2DZoBHC
d
thank you! is this:
listA.removeIf { objA -> objA.field1 !in listB.map { it.field1 } }
the same of this?
listA.filter { objA -> objA.field1 in listB.map { it.field1 } }
d
yup.. pretty much similar... the above is removing the items in-place whereas below is returning new filtered list 🙂
e
can use retainAll instead of removeIf to avoid double-negation, and map the list to a set once for performance: https://pl.kotl.in/ur4cbOd0T
d
true, separating list of field1 from listB is also preferable 😉
n
@ephemient that's interesting -- I would have done
asSequence().map { it.field1 }.toSet()
, but I might like your way better...undecided 🙂
d
is this:
val keepC = listB.mapTo(mutableSetOf()) { it.field1 }
equivalent to this?
val keepC = listB.map { it.field1 }.toSet()
and what is the difference between:
listA.retainAll { it.field1 in keepC }
and this ?
listA.filter { it.field1 in keepC }
n
in your first example, you get the same end result, but the second line (
listB.map
) creates an intermediate list that you don't need
in your second example, the first one mutates
listA
, while the second one returns a new list
d
very interesting, thanks!