user3318489 user3318489 -4 years ago 71
Java Question

Java get not containing Objects of List a in List b

Is there a better way of doing this - its such a boilderplate code.
I use Java 8 and I would do this with streams - but I would need some help doing this. I have tried it with ...removeIf() but it did not work.

final List<CalendarEventUserConnection> calendarEventUserConnectionsToDelete = new ArrayList<>();
for (final CalendarEventUserConnection existingCalendarEventUserConnection : existingCalendarEventUserConnections) {
boolean contains = false;
for (final CalendarEventUserConnection newCalendarEventUserConnection : calendarEventUserConnections) {
if (newCalendarEventUserConnection.getId() != null
&& newCalendarEventUserConnection.getId().equals(existingCalendarEventUserConnection.getId())) {
contains = true;
}
}
if (contains == false) {
calendarEventUserConnectionsToDelete.add(existingCalendarEventUserConnection);
}
}

Answer Source

You can streamify it up. It looks like you're filtering a list to see if anything in another list matches it, and collect the results in another list.

So you can use filter, anyMatch and collect.

final List<CalendarEventUserConnection> toDelete = existingCalendarEventUserConnections.stream()
    .filter(c -> !calendarEventUserConnections.stream()
                  .map(CalendarEventUserConnection::getId)
                  .anyMatch(id -> id!=null && id.equals(c.getId())))
    .collect(Collectors.toList());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download