Is there a way to remove an item from the first list (versions
) if no item meeting the condition is found.
here’s the condition:
s -> s.getId().equals(identifier) && s.getStatus().equals("CANCELLED").
here’s the iteration:
versions.stream()
.flatMap(v -> v.getDetails().stream())
.flatMap(m -> m.getStatuses().stream())
.filter(s -> s.getId().equals(identifier) && s.getStatus().equals("CANCELLED"))
4
If you want to remove from versions
any instance whose all innermost elements do not match a certain condition (id
equals to identifier
and status
equals to CANCELLED
), then you could:
- Employ a single
filter
on yourversions
list. - Stream the
details
of eachversion
. flatMap
the details’ status to have all the status corresponded to a singleversion
.- Finally, since we’ve used
filter
, negate the logic to keep (not remove) everyversion
that contains at least one object (not none) withid
equals toidentifier
andstatus
equals toCANCELLED
.
versions.stream()
.filter(v -> v.getDetails().stream()
.flatMap(d -> d.getStatus().stream())
.anyMatch(s -> s.getId().equals(identifier) && s.getStatus().equals("CANCELLED"))
)
.collect(Collectors.toList());
Here is a demo at OneCompiler.