Skip to content

Pattern Matching Inside a Stream

johnmcclean-aol edited this page Feb 24, 2016 · 4 revisions

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

Pattern Matching in Streams, Optional or other Monads

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

Example

 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.

Example

      Integer num = Stream.of(1)
						.flatMap(Matching.when().isValue(1).thenApply(i->i+10)
                        .when().isValue(2).thenApply(i->i).asStreamFunction())
						.findFirst()
						.get();

Stream of responsibility

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.

Example

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;
	}
	
}
Clone this wiki locally