-
Notifications
You must be signed in to change notification settings - Fork 51
Pattern Matching Inside a Stream
Cyclops has merged with simple-react. Please update your bookmarks (stars :) ) to https://github.com/aol/cyclops-react
All new develpoment on cyclops occurs in cyclops-react. Older modules are still available in maven central.
![screen shot 2016-02-22 at 8 44 42 pm](https://cloud.githubusercontent.com/assets/9964792/13232030/306b0d50-d9a5-11e5-9706-d44d7731790d.png)
Pattern Matching can be useful for making selections inside Streams (or other classes that allow composition via map & flatMap).
The Cases class, and all the builders are functions themselves, and so can be used inside map methods to make selections.
They return a value wrapped in an Optional by default. This opens the possibility for supplying a default value where none matched.
We can also make use of
- asUnwrappedFunction() : which unwraps the Optional result value. It will throw an exception if none exists.
- asStreamFunction() : which is somewhat safer in that it returns a Stream, and an empty Stream if no match was found.
asWrappedFunction() should be used in conjunction with map in Streams and flatMap in Optionals
Integer num = Stream.of(1)
.map(Matching.when().isValue(1).thenApply(i->i+10).asUnwrappedFunction())
.findFirst()
.get();
asStreamFunction() should be used in conjunction with flatMap in Streams and map in Optionals.
Integer num = Stream.of(1)
.flatMap(Matching.when().isValue(1).thenApply(i->i+10)
.when().isValue(2).thenApply(i->i).asStreamFunction())
.findFirst()
.get();
The ChainOfResponsibility interface combines a predicate and a function. It can be used in conjunction with Pattern Matching to select one option from a Stream.
In the example below, we will select the ChainOfResponsibility instance that matches 6<max (the second ChainImpl where Max is 7).
Stream<ChainImpl> chain = Stream.of(new ChainImpl(5,10),new ChainImpl(7,100));
int result = Matching.whenFromStream().streamOfResponsibility(chain).match(6).get();
@AllArgsConstructor
static class ChainImpl implements ChainOfResponsibility<Integer,Integer>{
int max;
int mult;
@Override
public boolean test(Integer t) {
return t<max;
}
@Override
public Integer apply(Integer t) {
return t*mult;
}
}