'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);
}
}
Solution 1:[1]
Your own search is O(NxM), where N is the number of elements in one list, and M in the other.
I suggest collecting all the IDs in the calendarEventUserConnections into a set.
Then you could collect all the elements in existingCalendarEventUserConnections whose ID is in that set into your deletion list.
Assuming your IDs are strings, this would be something like:
Set<String> idsToDelete = calendarEventUserConnections.stream()
.map( CalendarEventUserConnection::getId )
.filter( Objects::nonNull )
.collect(Collectors.toCollection(HashSet::new));
List<CalendarEventUserConnection> connectionsToDelete =
existingCalendarEventUserConnections.stream()
.filter( idsToDelete::contains )
.collect(Collectors.toList());
(Code untested)
Considering that you use a HashSet, this would reduce the complexity to O(M+N) instead of O(MxN)
Solution 2:[2]
If you want to obtain all Objects that are on listA and not on listB
public static <T> List<T> aNotB(List<T> listA, List<T> listB) {
List<T> result = new ArrayList(listA);
result.removeAll(listB);
return result;
}
This only works if the equals method of T is correctly implemented...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RealSkeptic |
| Solution 2 |
