dimanche 1 mars 2015



I have this unsafe code that could throw nullPtr exceptions:


Type t = objParam.getProject().getType();


How can I use java 8 optional and ifpresent()to return the least amount of code safely (one liner)?



// How can I modify this to return from the ifPresent()...or a better way in
// java8? how can I just return a string from the ifPresent() method?
// instead of on a separate if(...isPresent) <make the assignment>?
//
Optional<Obj> obj = Optional.ofNullable(objParam);
Optional<String> typeName = obj
.map(Project::getProject)
.map(Type::getType).ifPresent().getName(); // ??? how to get the type name ???



Aucun commentaire:

Enregistrer un commentaire