BiOptional
The class com.quartercode.quarterbukkit.api.BiOptional
basically provides an Optional that not only works with one, but instead two values at the same time. A non-empty BiOptional
guarantees to contain two non-null values. All empty instances contain no values at all. If you are interested what kind or purpose optionals serve in general, take a look at the official API documentation for the Optional
class linked above.
Obtaining a BiOptional
Since the BiOptional
API tries to imitate the Optional
API that you already know and love as much as possible, creating new instances of BiOptional
is pretty straightforward.
Empty instances
An empty instance, which of course doesn't contain any values at all, can be obtained using the following method:
BiOptional<A, B> opt = BiOptional.empty();
Non-empty instances
If you do have two values value1
and value2
, and you know both of them are always non-null, you can obtain a BiOptional
with those two values present using the following method:
BiOptional<A, B> opt = BiOptional.of(value1, value2);
If, however, at least one of your values could possibly be null, you need to use this method instead of the plain of()
one:
BiOptional<A, B> opt = BiOptional.ofNullables(value1, value2);
Using a BiOptional
Say that you've somehow got an instance of BiOptional
, i.e. because you called a method which returned it back to you. As with the single-value Optional
class, which is provided by the default JRE, there are several operations available to you.
Presence checking
If you just want to know whether both values are present or the instance is completely empty, you can use the following method:
boolean present = opt.arePresent();
If you want to execute a block of code if and only if the two values are present, and you wish to use those two values in your block of code, you can use this familiar method:
opt.ifPresent((value1, value2) -> /* do something */);
Filtering
The following method call deletes the two values and returns an empty BiOptional
if the provided BiPredicate
fails on the two values which are stored in the optional instance. Of course, if the optional is already empty, an empty instance is returned without any modifications.
opt = opt.filter((value1, value2) -> /* test something */);
A note on other operations
Please note that the other methods you expect from an optional (e.g. the get()
method) are not implemented since they would require the introduction of a generic pair class. At least for now, we don't plan on introducing such a class.