Skip to content

Optionals

johnmcclean-aol edited this page Nov 22, 2016 · 2 revisions

The Optionals class contains a lot of useful static methods for working with JDK Optional types.

Sequence

A sequence operation takes a List / Stream / Collection of Optionals and returns an Optional with a List / Stream / Collection of values. If any Optional supplied in the List / Stream or Collection the returned Optional is empty.

E.g. Sequence with one empty Optional

Optional<Integer> just = Optional.of(10);
Optional<Integer> none = Optional.empty();

Optional<ReactiveSeq<Integer>> maybes = Optionals.sequence(Stream.of(just, none, Optional.of(1)));
//Optional.empty();

E.g. Sequence with no empty Optionals

Optional<Integer> just = Optional.of(10);


Optional<ReactiveSeq<Integer>> maybes = Optionals.sequence(Stream.of(just, Optional.of(1)));
//Optional[ReactiveSeq[10,1]]

Accumulate Present

An alternative to sequence is to accumulate only the Optionals that are present and ignore the nulls.

In this example we can use the String concatonation Monoid to concat the the present Optional values.

Optional<String> just = Optional.of("10");
Optional<String> none = Optional.empty();
        
Optional<String> opts = Optional.accumulatePresent(Monoids.stringConcat,ListX.of(just, none, Optional.of("1")), 
                                                     );
//Optional.of("101")

Zip and combine

We can use Zip to combine an Optional with an Iterable or reactive-streams Publisher. Similarly we can use combine to combine an Optional with another Optional or cyclops-react Value type.

e.g.

Optionals.zip(Optional.of(10),Arrays.asList(20), this::add)
//Optional[30]
 
private int add(int a, int b) {
            return a + b;
}
Optionals.combine(Optional.of(10),Optional.of(20), this::add)
//Optional[30]

private int add(int a, int b) {
       return a + b;
}
Clone this wiki locally