【问题标题】:Filter a List<Object> based on List<String> inside each Object根据每个 Object 内的 List<String> 过滤 List<Object>
【发布时间】:2019-07-20 07:01:05
【问题描述】:

我有一个List&lt;Release&gt;,每个Release 都包含List&lt;Attachment&gt;

我想从每个List&lt;Attachment&gt; 中删除所有附件,除了XY 类型。 我想在 Java 8 中实现这一点。

我尝试了以下代码。但它不起作用。

releases = releases.stream()
                .filter(release -> release.getAttachments().stream()
                        .anyMatch(att -> AttachmentType.X_TYPE.equals(att.getAttachmentType())
                                        || AttachmentType.Y_TYPE.equals(att.getAttachmentType())))
                        .collect(Collectors.toList());

【问题讨论】:

  • removeIf 与倒置条件一起使用。
  • 请注意@michalk 回答下的cmets 中指出的removeIf

标签: java list java-8


【解决方案1】:

您可以遍历您的发布列表并使用removeIf 删除不需要的附件:

Predicate<Attachment> isNotXorY = attachment -> !(AttachmentType.X_TYPE.equals(attachment.getAttachmentType()) || AttachmentType.Y_TYPE.equals(attachment.getAttachmentType()));

releases.forEach(release -> release.getAttachments().removeIf(isNotXorY));

正如@roookeee removeIf 所指出的,时间复杂度是,因为它下面使用迭代器,它是remove 方法。

作为替代方案,您可以直接在集合上使用 forEach 并修改每个 Release

Predicate<Attachment> isXorY = attachment -> AttachmentType.X_TYPE.equals(attachment.getAttachmentType()) || AttachmentType.Y_TYPE.equals(attachment.getAttachmentType());

releases.forEach(release -> {
        List<Attachment> filteredAttachments = release.getAttachments()
                .stream()
                .filter(isXorY)
                .collect(Collectors.toList());
        release.setAttachments(filteredAttachments);
});

这个嵌套流可以被提取到一些辅助方法中以获得更好的可读性。

【讨论】:

  • 因为removeIf 采用谓词,因此可以通过在外部采用谓词来缩短
  • 请注意removeIf 的时间复杂度为O(n^2)(可能已通过ArrayList),因此使用filter 仅收集元素的简单流最好使用@ 987654334@特征
【解决方案2】:

您不需要在发布时使用文件管理器,因为您要删除附件而不是发布。对附件使用过滤器。使用 release.stream().map 和 attachments.stream().filter

【讨论】:

  • 我知道我可以使用 ForEach,我试图避免使用 forEach。谢谢@Aman
  • @akapti,您首先必须了解每种流方法。过滤器用于根据条件删除或保留集合中的元素。 ‘AnyMatch’ 或 ‘firstMatch’ 将返回与您的情况不合适的条件匹配的第一个元素。
  • 感谢您的回复。我是 java 8 的初学者。
猜你喜欢
  • 2018-09-22
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 2021-04-29
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多