Optional Java Best Practice Reddit

Optional java best practice reddit

If course you can templatize it, using the magic of lambdas!

Start with an to define the lambda's contract:

This is a Single Method Interface (or SMI) that will encapsulate the behaviour of your method.

Now create a utility method to use the SMI:

Now, using an in your calling code, your method above becomes:

So here, is a lambda that captures the retrieval behaviour. The is allowed to throw a so the lambda is too.

Alternatively, I would use the other method of - - and change the code as follows:

This has the advantage of being simpler, but the disadvantage of simply discarding other results if there are any.

Java Optional, NullPointerException Killer? Part 1