Simple rule engine updated

I have taken the time to upgrade my simple Java rule engine so that it supports Java 8 lambdas and streams and it is now published in Maven Central. The code is now also available on GitHub.

First off, the Maven dependencies. The following dependency is for the basic rule engine which is compatible with Java 6.


If you want to use lambdas from Java 8, then you need to also add a dependency as follows:


This allows you to write code like that found on lines 15 and 20.

Rule rule1 = new Rule("R1", 
            " == \"ant\" && == \"clare\"", 
            "Règle spéciale pour famille Kutschera");
Rule rule2 = new Rule("R2", "true", "outcome2", 1, 
                      "ch.maxant.produits", "Régle par défault");
List<Rule> rules = Arrays.asList(rule1, rule2);

//to use a lambda, construct a SamAction and pass it a lambda.
IAction<MyInput, BigDecimal> action1 = 
        new SamAction<MyInput, BigDecimal>(
            i -> new BigDecimal("100.0")
IAction<MyInput, BigDecimal> action2 = 
        new SamAction<MyInput, BigDecimal>(
            i -> new BigDecimal("101.0")

List<IAction<MyInput, BigDecimal>> actions = 
                                 Arrays.asList(action1, action2);

Engine e = new Engine(rules, true);

MyInput input = new MyInput();
Person p1 = new Person("ant");
Person p2 = new Person("clare");

BigDecimal price = e.executeBestAction(input, actions);
assertEquals(new BigDecimal("101.0"), price);

If you want to pass a Stream
to the Engine rather than a Collection, then use the sub-class found in the second library, for example:

Stream<Rule> streamOfRules = getStreamOfRules();

//to pass in a stream, we need to use a different Engine
Java8Engine e = new Java8Engine(streamOfRules, true);

//use this engine as you would the normal Engine

See the tests on GitHub for more details. In theory, you can pass in a parallel stream – I haven’t tried it but would be interested to hear about your successes / failures.

Finally, if you are using Scala, there is still support for that too, in the ScalaEngine which can be found in the following dependency. See the tests on GitHub for more details.


Copyright ©2014, Ant Kutschera

Leave a Reply

Your email address will not be published.