https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Daniele B

08/10/2020, 11:42 PM
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

deactivateduser

08/10/2020, 11:49 PM
is this what you need? https://pl.kotl.in/EK2DZoBHC
d

Daniele B

08/10/2020, 11:54 PM
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

deactivateduser

08/10/2020, 11:56 PM
yup.. pretty much similar... the above is removing the items in-place whereas below is returning new filtered list 🙂
e

ephemient

08/10/2020, 11:57 PM
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

deactivateduser

08/10/2020, 11:58 PM
true, separating list of field1 from listB is also preferable 😉
n

nanodeath

08/11/2020, 12:35 AM
@ephemient that's interesting -- I would have done
asSequence().map { it.field1 }.toSet()
, but I might like your way better...undecided 🙂
d

Daniele B

08/11/2020, 12:41 AM
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

nanodeath

08/11/2020, 12:45 AM
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

Daniele B

08/11/2020, 12:47 AM
very interesting, thanks!