Java Streams checking for nulls -


i want convert piece code streams

list<ecsusu> listofusus = msccrequest.getusedserviceunit(); if (listofusus != null) {      ecsusu usedserviceunit = listofusus.get(0);      if (usedserviceunit.getcctime() != null && usedserviceunit.getcctime() > 0) {           return unittype.seconds;       } else {           return unittype.bytes;       } } 

i thought work getting nullpointerexception. msccrequest.getusedserviceunit() might return null , that's why need check

 msccrequest.getusedserviceunit().stream()                     .filter(list -> list != null)                     .limit(1)                     .map(usedserviceunit -> {                         if (usedserviceunit.getcctime() != null && usedserviceunit.getcctime() > 0) {                             return unittype.seconds;                         } else {                             return unittype.bytes;                         }                     }); 

if msccrequest.getusedserviceunit() returns null, attempt call stream() method on throw nullpointerexception. expect npe comes that. need check null before calling stream() method.

also note 2 pieces of code not equivalent (even if above problem fixed). first code checks first element of list, while second takes first non-null element.

also, interested in single element of list. findfirst seems better choice limit.

list<ecsusu> listofusus = msccrequest.getusedserviceunit(); if (listofusus != null) {     return listofusus.stream()         .filter(objects::nonnull)         .findfirst()         .map(usedserviceunit -> {                 if (usedserviceunit.getcctime() != null && usedserviceunit.getcctime() > 0) {                     return unittype.seconds;                 } else {                     return unittype.bytes;                 }             })         .orelse(/* default value */); } 

Comments