问题
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?
回答1:
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.
回答2:
Another way without accumulates:
rule "Oldest Child"
when
$person: Person()
$oldestChild: Person() from $person.children
not Person(dateOfBirth > $oldestChild.dateOfBirth) from $person.children
then
insert($oldestChild)
end
I think that this solution could perform worse than Laune's though.
来源:https://stackoverflow.com/questions/28994984/how-to-get-max-min-item-from-a-list-in-drools