Search code examples
javadrools

How to get max min item from a list in Drools


I have a class

class Person {
    public Date dateOfBirth;
    public List<Person> children;
}

I would like to create a Drools rule that gets me the oldest child. For example:

rule "Oldest Child"
    when
        $person: Person()
        $oldestChild: Person() from $person.children
    then
        insert($oldestChild)
end

As written, $oldestChild is a list but I'd really like to be an actual oldest child (single object instead of a list). I played around with accumulate a bit but couldn't get it to work. Any ideas?


Solution

  • An accumulate with inline custom code produces the oldest child:

    rule "oldest child"
    when
      Person($pn: name, $pd: dateOfBirth, $children: children)
      Person($ocn: name) from accumulate(
        $child: Person( $cd: dateOfBirth) from $children,        
        init( Person minp = null; Date mind = new Date(); ),
        action( if( $cd.compareTo( mind ) < 0 ){
                    minp = $child;
                    mind = $cd;
                } ),
        result( minp ) )
    then
      System.out.println( $pn + "'s oldest child is " + $ocn );
    end
    

    You may implement your own accumulate function (in Java) if you need this for serious work - it is more work but the "cleaner" solution. See the docs.