2
votes

I am trying to sort a list of objects using a set of rules defined in drools rules engine. The sample object structure is as follows

public class A {

   String name;
   Date createdDate;

}

I want to

  1. Define a set of rules for sorting a list of objects .
    Ex : rule 1 : "Sort objects using name ascending"
           rule 2 : "Sort objects using createdDate descending"

  2. Define the order which the rules needs to be executed .
    Ex : set order 1 to rule 1
           set order 2 to rule 2
    So the objects will be sorted by name ascending and createdDate descending.

Can I achieve this using the drools engine ?
I thought of using the compareTo() for the sorting but since the sorting criteria can be changed at runtime the logic is becoming complex and hard to maintain.

Thanks,
Kolitha.

2

2 Answers

3
votes

Drools does not sort objects the way quicksort or some similar sorting algorithm rearranges objects within an array or some other aggregate. What you can do is to have a rule fire, repeatedly, once for each fact from a set of facts (such as your class A objects) and with constraints guaranteeing this happening in a certain order. Also, you need to keep track of facts that have already been processed.

Therefore, the question to be answered first is: why do you need the objects in a certain order?

If the facts need to be processed in this order, you don't have to sort them in the ususual sense of the word, and the aforementioned rule would be sufficient:

declare ListOfA
    listOfA: List
end

rule noListOfA
when
    not ListOfA()
then
    ListOfA loa = new ListOfA();
    loa.setListOfA( new ArrayList() );
    insert( loa );
end

rule sortA
when
    $a: A( $name: name, $createdDate: createdDate )
    $loa: ListOfA( $listOfA: listOfA not contains $a )
    not A( this != $a, this not memberOf $listOfA,
                       name < $name ||
                       name == $name && createdDate > $createdDate )
then
    System.out.println( $a );
    modify( $loa ){ getListOfA().add( $a ) }
end
0
votes

This is the way to sort in drools.

rule "Rule 03"
    when
        $number : Number( )
        not Number( intValue < $number.intValue )
    then
        System.out.println("Number found with value: " + $number.intValue() ); 
        retract( $number );
end