Search code examples
javadrools

Drools Get Object That Has The Higher Priority


I want to know if we could get the object that has the higher priority using drools accumulate expression? Here is my code:

rule "dropShiftWithTheLowestPriorityTaskForWeekdayMorningShiftReassignment"
when 
    ShiftAssignment( isNeedToReassign == true, shiftType.code == 'E', weekend == false,  
        $shiftDate : shiftDate, 
        $shiftType : shiftType )

    $max : Number(intValue >= 0) from accumulate(
        $assignment : ShiftAssignment(
            weekend == false,
            shiftDate == $shiftDate,
            shiftType == $shiftType, 
            $totalWeight : totalWeight),
        max($totalWeight)
    )
then
    System.out.println('----------');
    System.out.println('max='+$max);

I just get the max totalWeight, but I don't know how I can get the object that contains that totalWeight. Please help me, thank you.


Solution

  • There was a similar question posted some days ago: How to get max min item from a list in Drools

    There are 2 solutions posted there:

    1. Create your own accumulate function
    2. Use 2 simple patterns

    Following the first approach, you would need to write something like this:

    when
        $maxAssignment: ShiftAssignment() from accumulate(
            $sa: ShiftAssignment(),        
            init( ShiftAssignment max = null; ),
            action( if( max == null || max.totalWeight < $sa.totalWeight ){
                max = $sa;
            } ),
            result( max ) )
    then
        //$maxAssignment contains the ShiftAssignment with the highest weight. 
    end
    

    Please note that this implementation should be used only for prototyping or testing purposes. It is considered a good practice to implement your custom accumulate functions in Java.

    Following the second approach, your rule could be re-written as:

    when 
        $maxAssignment: ShiftAssignment(..., $maxWeight: totalWeight)
        not ShiftAssignment(..., totalWeight > $maxWeight)
    then
        //$maxAssignment contains the ShiftAssignment with the highest weight. 
    end
    

    Hope it helps,