Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert using JAVA 8 Streams

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.

like image 607
user3525434 Avatar asked Nov 25 '16 11:11

user3525434


2 Answers

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>
like image 189
Anton Balaniuc Avatar answered Oct 02 '22 22:10

Anton Balaniuc


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.

like image 24
s_bei Avatar answered Oct 02 '22 22:10

s_bei