2017-02-28 86 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)

相关问题