我有一个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());发布于 2019-07-20 15:12:16
您可以迭代您的发布列表,并使用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);
});为了获得更好的可读性,可以将这个嵌套的流提取到某个辅助方法中。
发布于 2019-07-20 15:04:09
你不需要在发布时使用filer,因为你想要删除附件,而不是发布。对附件使用筛选。使用release.stream().map和attachments.stream().filter
https://stackoverflow.com/questions/57122519
复制相似问题