How to convert following method to java 8?

  • A+
Category:Languages

I have List object and I need to take the first element on the list if it is not null or empty.

I write below code using java and now I want to convert it to Java 8.

    List<DD> container     A<DD,DI> a;     if(container!=null || !container.isEmpty()){        for(DD dd:container)        {           a = dd.getPrescription();           break;        }     } 

I convert it like this.

 DD detail = container.stream().findFirst().get(); 

I need to know this is correct?

 


There is a critical flaw in your current code, i.e.

if(container!=null || !container.isEmpty()) 

this can still throw a NullPointerException (when container == null), unless the conditional operator is changed to &&. Post which the implementation below would be what I would suggest following.


It's almost correct, in the sense that you need to handle some default value if the conditions are not met :

DD detail = container.stream().findFirst().orElse(null); // or some default value instead of 'null' 

If the container itself could be null, use

DD detail = container != null ?                  container.stream().findFirst().orElse(null) : null; 

In the case when you need the prescription from this object, use map as :

container.stream().findFirst().map(DD::getPrescription).orElse(null) //                               ^^ //                               return type of prescription then 

With Java-9, this could have been much simpler as :

A<DD, DI> basePrescription = Stream.ofNullable(container) // Java-9 API                                    .flatMap(List::stream)                                    .findFirst()                                    .map(DD::getPrescription)                                    .orElse(null); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: