![](/img/trans.png)
[英]Guava: get a list of variables from a list of objects containing the variable
[英]Java get not containing Objects of List a in List b
有沒有更好的方法來做到這一點 - 它是這樣的樣板代碼。 我使用 Java 8 並且我會使用流來執行此操作 - 但我需要一些幫助來執行此操作。 我已經嘗試過...removeIf() 但它沒有用。
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);
}
}
你可以流化它。 看起來您正在過濾一個列表以查看另一個列表中的任何內容是否匹配它,並將結果收集到另一個列表中。
所以你可以使用filter
、 noneMatch
和collect
。
final List<CalendarEventUserConnection> toDelete = existingCalendarEventUserConnections.stream()
.filter(c -> calendarEventUserConnections.stream()
.map(CalendarEventUserConnection::getId)
.noneMatch(id -> id!=null && id.equals(c.getId())))
.collect(Collectors.toList());
如果要獲取 listA 上而不是 listB 上的所有對象
public static <T> List<T> aNotB(List<T> listA, List<T> listB) {
List<T> result = new ArrayList(listA);
result.removeAll(listB);
return result;
}
這只有在正確實現了T
的equals
方法時才有效...
您自己的搜索是 O(NxM),其中 N 是一個列表中的元素數,而另一個是 M。
我建議將calendarEventUserConnections
中的所有 ID 收集到一個集合中。
然后,您可以將existingCalendarEventUserConnections
中其 ID 位於該集合中的所有元素收集到您的刪除列表中。
假設您的 ID 是字符串,這將類似於:
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());
(代碼未經測試)
考慮到您使用HashSet
,這會將復雜度降低到 O(M+N) 而不是 O(MxN)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.