Reputation: 51
I've tried to change this code to Java 8 streams. My code looks like this:
for(D d : n.getD()) {
for(M m : d.getT().getM()) {
if(m.getAC().contains(this)) {
return d;
}
}
}
and I want to convert it to java 8 streams. I've started like this:
n.getD().stream()
.map(m -> m.getT().getM())
but then I don't know if I should map again, or use a filter.
Upvotes: 5
Views: 207
Reputation: 3093
I don't know about your domain, but to keep it readable I would probably delegate and simplify to something like this:
return n.getD().stream()
.filter(d -> d.getT().containsAC(this))
.findFirst()
.orElse(null);
And then in class T add the delegation method:
public boolean containsAC(AC ac) {
return m.stream().anyMatch(m -> m.getAC().contains(ac));
}
Upvotes: 1
Reputation: 11739
Other possible way is to use anyMatch
instead of second filter
return n.getD().stream().filter(
d -> d.getT().getM().stream().anyMatch(
m -> m.getAC().contains(this)
)
).findFirst(); // result will be Optional<D>
Upvotes: 4
Reputation: 12523
one way to handle this:
return n.getD().stream().filter(d -> d.getT().getM().stream().filter(m -> m.getAC().contains(this)).findFirst().isPresent()).findFirst();
in this case a null value is possible.
Upvotes: 2