15.3_Returning an Optional Flashcards
📝️ What is an Optional?
Optional is a container object used to contain not-null objects. (Think of it as a box)
📝️ How do we express this “we don’t know” or “not applicable” answer in Java?
-> By using an Optional
📝️ How to create an Optional?
-> By using its Factory Methods…
-> You can either request an empty Optional or pass a value for the Optional to wrap [empty | of+Nullable]
:: Optional.empty();
:: Optional.ofNullable({average});
:: Optional.of({average}); //⚠️ If T isNull throws a NPE
📝️ How to get an Optional the hardWay?
🕵♂️️ Optional avgOpt = ({average} == null)
? Optional.empty()
: Optional.of({average});
📝️ How to check whether a value is there and/or get it out of the box?
[isPresent | get]
…
boolean isPresent()
T get()
🤯️⚠️📣️ If we do a get() and the Optional is empty -> Throws java.util.NoSuchElementException
📝️ What are the Optional Instance methods?
ifPresent | ifPresentOrElse
or + Else + {Get | Throw}
filter
map | flatMap