Skip to content

Pattern Matching Within a Stream

johnmcclean-aol edited this page Jan 20, 2016 · 5 revisions

LazyFutureStream has a pattern matching operator. This operator behaves like a 'decisioning' map or transform operator. The mapping to be applied can be differentiated by properties of incoming elements in the Stream.

Examples

Even and Odd

For example to convert numbers into Strings even or odd, we can pattern match of the incoming Integers applying a different mapping function for even numbers than for odd ones.

List<String> result = LazyFutureStream.of(1,2,3,4)
                               .capture(e->e.printStackTrace())
                               .patternMatch("",
                                 c->c.hasValuesWhere( (Integer i)->i%2==0 ).then(i->"even"),
                                 c->c.hasValuesWhere( (Integer i)->i%2!=0).then(i->"odd")
                                )
                                .toList();
//List["odd","even","odd","even"]

One, Two, Many

As another example, lets expand our cases to three, and this time organise our numbers into groups of three - "one", "two" or "many". By matching on the numbers 1 and 2, we can convert those to English text directly. We can also make use of the defaultValue parameter to set all other values to many (if assume values > 0).

List<String> result = LazyFutureStream.of(1,2,3,4)
                               .capture(e->e.printStackTrace())
                               .patternMatch("many",
                                  c->c.hasValuesWhere( (Integer i)->i==1 ).then(i->"one"),
                                  c->c.hasValuesWhere( (Integer i)->i==2).then(i->"two")
                               )
                               .toList();
//List("one","two","many","many")

Destructuring / Decomposition example

Pattern matching can also match on the internal contents of a supplied element

List<String> result = LazyFutureStream.of(new MyCase2(1,2),new MyCase2(3,4))
                                      .capture(e->e.printStackTrace())
                                      .patternMatch("n/a",
                                        c->c.hasValues(1,2).then(i->"one"),
                                        c->c.hasValues(3,4).then(i->"two"),
                                        c->c.hasValues(5,6).then(i->"three")
                                      )
                                      .toList();
//List["one","two"]

//Where MyCase2 has the following fields 

static class MyCase2 {
    int first;
    int second;
}

See also

Clone this wiki locally