I'm fairly new to Java8. I have a requirement to subtract/remove POJOs in one list based on certain criteria (from another list) and show it on UI.
Iterate one list and search for condition Remove the object Send the original list to UI
Children.java
private String firstName;
private String lastName;
private String school;
private String personId;
// Setters and getters.
Person.java
private String personId;
private String fullName;
private String address;
// Setters and Getters.
..MAIN CODE..
// populated by other methods.
List<Person> personList;
//Connect to DB and get ChildrenList
List<Children> childrenList = criteria.list();
for(Children child : childrenList) {
personList.removeIf(person -> child.getPersonId().equals(person.getPersonId()));
}
Is there any BETTER way to HANDLE for-loop? Any help is appreciated.
The code that you have right now works perfectly, but is also
O(n * m)
sinceremoveIf
iterates through theList
for everyChildren
. One way to improve would be to store every child'spersonId
in aSet<String>
and remove everyPerson
from theList<Person>
if theirpersonId
is contained in theSet
:Just another way of doing same but without mutating the original list:
It should have a bit of increased space complexity but you could take advantage of
parallelStream
here.