Remove certain elements in one list based on condition from another list
The code that you have right now works perfectly, but is also O(n * m)
since removeIf
iterates through the List
for every Children
. One way to improve would be to store every child's personId
in a Set<String>
and remove every Person
from the List<Person>
if their personId
is contained in the Set
:
Set<String> childIds = childrenList.stream()
.map(Children::getPersonId)
.collect(Collectors.toSet());
personList.removeIf(person -> childIds.contains(person.getPersonId()));
Just another way of doing same but without mutating the original list:
Set<String> childIds = childrenList.stream()
.map(Children::getPersonId)
.collect(Collectors.toSet());
personList = personList.stream().filter(person ->
!childIds.contains(person.getPersonId())
).collect(Collectors.toList());
It should have a bit of increased space complexity but you could take advantage of parallelStream
here.