Convert Using JAVA 8 Streams

I tried changing this code to Java 8 threads. My code is as follows:

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 threads. I started like this:

  n.getD().stream() .map(m -> m.getT().getM()) 

but then I donโ€™t know if I should display the map again or use a filter.

+5
source share
3 answers

Another possible way is to use anyMatch instead of the second filter

 return n.getD().stream().filter( d -> d.getT().getM().stream().anyMatch( m -> m.getAC().contains(this) ) ).findFirst(); // result will be Optional<D> 
+4
source

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.

+2
source

I donโ€™t know about your domain, but for it to be readable, I would probably delegate and simplify something like this:

 return n.getD().stream() .filter(d -> d.getT().containsAC(this)) .findFirst() .orElse(null); 

And then in class T add a delegation method:

 public boolean containsAC(AC ac) { return m.stream().anyMatch(m -> m.getAC().contains(ac)); } 
+1
source

Source: https://habr.com/ru/post/1260343/


All Articles