How to get max min item from a list in Drools

╄→гoц情女王★ 提交于 2019-12-13 01:35:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!