Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 903
Srinivas Lakshman Avatar asked Feb 27 '18 20:02

Srinivas Lakshman


People also ask

How do you remove an element from a list based on condition?

To remove elements from ArrayList based on a condition or predicate or filter, use removeIf() method. You can call removeIf() method on the ArrayList, with the predicate (filter) passed as argument. All the elements that satisfy the filter (predicate) will be removed from the ArrayList.


2 Answers

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()));
like image 63
Jacob G. Avatar answered Oct 25 '22 20:10

Jacob G.


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.

like image 39
Vinay Prajapati Avatar answered Oct 25 '22 20:10

Vinay Prajapati