【问题标题】:How to get elements from List A that don't exist in List B如何从列表 A 中获取列表 B 中不存在的元素
【发布时间】:2019-07-24 13:42:40
【问题描述】:

我想过滤列表 A 中不存在于列表 B 中的所有对象。如何使用 Java Stream 来实现?

List<MyClass> A
List<MyClass> B

我想按 MyClass.id 字段过滤

我的尝试:

List<MyClass> actionsToRemoval = A.stream()
                .filter(oldAction -> B.stream()
                        .noneMatch(action -> action.getId() != null && action.getId().equals(oldAction.getId()))).collect(
                        Collectors.toList());

但结果与我的预期相反

更新:

我的 DEV 代码:

来自数据库的数据:

private void removeUnnecessaryCorrectiveActions(List<IncidentCorrectiveActionDto> correctiveActionsDto) 
{
//correctiveActionsDto - data from Frontend, for exampe that object contains 3 objects with id=1 (this object should be updated), id=2 (new object), id=3 (ne w object)
List<IncidentCorrectiveAction> oldActions = incidentCorrectiveActionRepository
                .findByIncidentId(id)
//oldActions -> for example one object with id=1, fetched from database

    List<IncidentCorrectiveAction> actionsToRemoval = oldActions.stream()
                    .filter(oldAction -> correctiveActionsDto.stream()
                            .noneMatch(action -> action.getId() != null && action.getId().equals(oldAction.getId()))).collect(
                            Collectors.toList());

所以在这种情况下,我的 List actionsToRemoval 应该返回 0 个元素,因为我们想添加 2 个新元素并将它们保存在数据库中。

另一种情况: oldActions -> 3 个 id=1, id=2, id=3 的对象

correctiveActionsDto(来自前端的对象)-> 包含 1 个 id=1 的对象

在这种情况下,actionToRemoval 列表应返回 2 个元素:id= 2 和 id = 3,因为这些对象应从数据库中删除。

【问题讨论】:

  • 我无法重现您的问题。你的代码对我有用。您能否分享一个minimal, reproducible example,包括两个列表的内容,以便我们重现您的问题?

标签: java lambda filter java-8 java-stream


【解决方案1】:
List<MyClass> FilteredOutput =
              A.stream()
              .filter(e -> B.stream().map(MyClass::getid).anyMatch(id -> 
              id.equals(e.getid())))
              .collect(Collectors.toList());

将列表A 作为流,然后从A 获取ID 与B 的ID 进行比较。

【讨论】:

    【解决方案2】:

    最好的方法是将谓词逻辑封装在对象的 equals 方法中,然后使用 B.contains(x) 作为过滤器。 比如:

    class MyClass{
       private Integer id;
       ...
       public boolean equals(Object other){
         return other instanceof MyClass && other.getId() != null && other.getId().equals(this.id);
    } 
    
    

    然后:

    List<MyClass> A = ...;
    List<MyClass> B = ...;
    
    List<MyClass> diffAB = A.stream().filter(v -> !B.contains(v)).collect(Collectors.asList());
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2022-08-19
      相关资源
      最近更新 更多