Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove objects from a List based on their path

I have two lists:

private final List<EventTeaserModel> events = new ArrayList<>();
private final List<EventTeaserModel> premiumEventList = new ArrayList<>();

The use case for my method removePremiumEventsFromEvents() is to remove premiumEventList objects from the events List (remove objects with the same path).

Here is what I tried and it works. Is there a better way to do it in Java?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

private void removePremiumEventsFromEvents() {
            for (EventTeaserModel premiumEvent: premiumEventList) {
                List<EventTeaserModel> findDuplicatedEvent = events.stream()
                        .filter(event -> event.getResource().getPath().equals(premiumEvent.getResource().getPath()))
                        .collect(Collectors.toList());
                events.removeAll(findDuplicatedEvent);
            }
        }

Thanks to @Chaosfire I was able to simplify it like:

private void removePremiumEventsFromEvents() {
        for (EventTeaserModel premiumEvent : premiumEventList) {
            events.removeIf(event -> event.getResource().getPath().equals(premiumEvent.getResource().getPath()));
        }
    }

>Solution :

This solution is kinda similar to yours conceptually, but it looks a bit cleaner.
You can first find all paths in premiumEventList, then use removeIf on events for each of the paths. Like this:

private void removePremiumEventsFromEvents() {
    premiumEventList.stream()
        .map(EventTeaserModel::getResource)
        .map(Resource::getPath)
        .forEach(path -> events.removeIf(event -> 
            event.getResource().getPath().equals(path)));
}

Personally however, I like to keep my lists unmodifiable/immutable. So I would instead create a new events list with the elements filtered. Like this:

private void removePremiumEventsFromEvents() {
    final Set<String> paths = premiumEventList.stream()
        .map(EventTeaserModel::getResource)
        .map(Resource::getPath)
        .collect(Collectors.toSet());

    // Or preferrably, return the new list.
    events = events.stream()
        .filter(event -> !paths.contains(event.getResource().getPath()))
        .collect(Collectors.toList());
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading