根据每个对象

时间:2019-07-20 07:01:05

标签: java list java-8

我有一个List<Release>,每个Release包含List<Attachment>

我想从List<Attachment>X类型中除去每个Y的所有附件。 我想在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());

2 个答案:

答案 0 :(得分:3)

您可以遍历发布列表并使用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指出,时间复杂度为O(n^2),因为在其下面使用了迭代器及其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);
});

可以将此嵌套流提取到某种辅助方法中,以提高可读性。

答案 1 :(得分:0)

您无需在发布时使用Filer,因为您要删除未发布的附件。在附件上使用过滤器。使用release.stream()。map和annexs.stream()。filter