Java 8 Optional is Not Just for Replacing a null Value
Join the DZone community and get the full member experience.
Join For FreeIn Java 8, you can return an Optional instead of return null; as you might do in Java 7. This may or may not make a big difference depending on whether you tend to forget to check for null or whether you use static code analysis to check to nullalbe references.
However, there is a more compelling case which is to treat Optional like a Stream with 0 or 1 values.
Simple Optional Use Case
String text = something(); if (text != null) {
Optional text = something(); if (text.isPresent()) { String text2 = text.get();
Optional text = something(); if (text != null && text.isPresent()) { String text2 = text.get();
A more complex example
static String getFirstSecondThird(Nested nested) { try { return ((Contained2) nested.first.second).get(0).third; } catch (NullPointerException | ClassCastException | IndexOutOfBoundsException ignored) { return null; } }
static Optional getFirstSecondThird(Optional nested) { return nested // could be non-present .map(x -> x.first) // could be null .map(x -> x.second) // could be null // could be another type .map(x -> x instanceof Contained2 ? (Contained2) x : null) .map(x -> x.list) // could be null .filter(x -> !x.isEmpty()) // could be empty .map(x -> x.get(0)) // could be null .map(x -> x.third); // could be null. }
Conclusion
Additional
static class Nested { Contained first; } static class Contained { IContained2 second; } interface IContained2 { } static class Contained2 implements IContained2 { List list; } static class Data { String third; }
Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments