0

How can I find the most recent date among all joining dates in a Drools object?

My rule is something like this:

declare RecentDate
      dates : java.util.Date
end

rule "insert_dates"
      when
       //reading dates from back end
       Employee($date : dateOfJoining, $name : name, salary > 10000)
       then
       insert(new RecentDate($date))
end

Now I would like to find the most recent employee based on dateOfJoining. Any help is appreciated. Thank you.

Sunil
  • 101
  • 1
  • 10

1 Answers1

0

One way to do it is to, given an employee, make sure that there is no other with a higher date:

declare RecentDate
      dates : java.util.Date
end

rule "insert_dates"
when
  //reading dates from back end
  Employee( $date : dateOfJoining, $name : name, salary > 10000)
  not Employee (dateOfJoining > $date)
then
  insert(new RecentDate($date))
end

The rule above only works on the case you have all your Employee facts in your session before you execute fireAllRules(). If this is not the case, you can try to initially insert a RecentDate with a null date and then compare each Employee against it and update it accordingly:

rule "Init RecentDate"
when
  not RecentDate()
then
  insert new RecentDate(null);
end

rule "update_dates"
when
  Employee( $date : dateOfJoining, $name : name, salary > 10000)
  $d: RecentDate ( date == null || date < $date)
then
  modify ($d){
    setDate($date)
  }
end

Hope it helps,

Esteban Aliverti
  • 6,259
  • 2
  • 19
  • 31
  • Thank you so much for your response. I have tried in this way. But RecentDate() object containing all dates after inserting . I have created another rule to print date in RecentDate(), But it is printing all dates for employees salary > 10000. My requirement is to find only the most recent date. – Sunil Mar 28 '19 at 01:58
  • Hmmm... How are you inserting your facts and when are you calling `fireAllRules()`? Are you calling `fireAllRules()` after each `Employee` you insert? – Esteban Aliverti Mar 28 '19 at 05:40
  • I've added a second way that is not affected by the order of insertion and execution of the facts and rules. – Esteban Aliverti Mar 28 '19 at 05:57