2017-02-28 43 views
-1

有沒有更好的方法來做到這一點 - 它是這樣一個boilderplate代碼。 我使用Java 8,我會用流做到這一點 - 但我需要一些幫助做到這一點。我嘗試過... removeIf()但它沒有工作。Java不包含列表中的對象列表b

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); 
     } 
    } 
+1

有沒有更好的方式來提出這個問題?它幾乎不包含任何信息。 – Adam

+0

這樣做 - 什麼是「這個」?如果你無法解釋,我們肯定不會是 –

+0

是的。不要使用20個以上的字符變量名稱。不要使用'== false'。這就是'!'操作符的用途。 –

回答

1

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

所以你可以使用filter,anyMatchcollect

final List<CalendarEventUserConnection> toDelete = existingCalendarEventUserConnections.stream() 
    .filter(c -> !calendarEventUserConnections.stream() 
        .map(CalendarEventUserConnection::getId) 
        .anyMatch(id -> id!=null && id.equals(c.getId()))) 
    .collect(Collectors.toList()); 
+0

@assylias好主意。謝謝 – khelwood

0

如果你想獲得上和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方法正確實現這僅適用於所有對象...

+0

結果取決於如何實現'equals',這可能與問題中的邏輯不同。 – assylias

+0

但這個問題在這方面非常開放......而其他人......我認爲「等於」是正確實施的。 –

+1

這個問題比較了對象的* id *,這意味着實際的對象可能甚至沒有'equals'覆蓋。 – RealSkeptic

0

您自己的搜索是O(NxM),其中N是一個列表中元素的數量,另一個是M。

我建議將calendarEventUserConnections中的所有ID收集到一個集合中。

然後,您可以將existingCalendarEventUserConnections中的所有元素收集到您的刪除列表中。

假設你的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)

相關問題