15.3_Returning an Optional Flashcards

1
Q

📝️ What is an Optional?

A

Optional is a container object used to contain not-null objects. (Think of it as a box)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

📝️ How do we express this “we don’t know” or “not applicable” answer in Java?

A

-> By using an Optional

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

📝️ How to create an Optional?

A

-> 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

📝️ How to get an Optional the hardWay?

A

🕵‍♂️️ Optional avgOpt = ({average} == null)
? Optional.empty()
: Optional.of({average});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

📝️ How to check whether a value is there and/or get it out of the box?

A

[isPresent | get]

boolean isPresent()
T get()

🤯️⚠️📣️ If we do a get() and the Optional is empty -> Throws java.util.NoSuchElementException

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

📝️ What are the Optional Instance methods?

A

ifPresent | ifPresentOrElse
or + Else + {Get | Throw}
filter
map | flatMap

How well did you know this?
1
Not at all
2
3
4
5
Perfectly