Search code examples
javalambdaforeachjava-8java-stream

Remove certain elements in one list based on condition from another list


I'm fairly new to Java 8. I have a requirement to subtract/remove POJOs in one list based on certain criteria (from another list) and show it on UI.

  1. Iterate one list and search for condition
  2. Remove the object
  3. 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 the for-loop?


Solution

  • 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()));