簡體   English   中英

Java 獲取列表 b 中不包含列表 a 的對象

[英]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);
        }
    }

你可以流化它。 看起來您正在過濾一個列表以查看另一個列表中的任何內容是否匹配它,並將結果收集到另一個列表中。

所以你可以使用filternoneMatchcollect

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;
}

這只有在正確實現了Tequals方法時才有效...

您自己的搜索是 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM