Search code examples
listuniquedroolsitems

Drools: how to get a list with items with unique ids


I have a complex object in Drools. Object A contains a list of objects B. Object B contains a list of objects C.

Object C has a property id. Object Cs can occur on different object Bs with the same id.

I need to be able to count the number of unique ids in A.

My current rule works when the id is not repeated. But how do I get a listOfC without duplicate ids?

rule CountCs
    dialect "mvel"
    when
       a : A( )

       listOfC: List( ) from accumulate (
           b : B( ) from a.bItems
           and
           c : C( ) from b.cItems;
           collectList( c )
       )
       eval( listOfC > 2)
    then
       // do whatever
    end

Solution

  • If you are only interested in the number of occurrences, and not in the occurrences themselves, then you can use a Set to collect your ids. The Set will take care of eliminating the duplicates for you (assuming your ids implement the corresponding identity and equality checks):

    rule CountCs
    dialect "mvel"
    when
     a : A( )
     setOfC: Set( size > 2 ) from accumulate (
       b : B( ) from a.bItems
       and
       c : C( ) from b.cItems;
       collectSet( c.id )
     )
    then
      // do whatever
    end
    

    Note that I included the evaluation of the size of the set in the same pattern. You don't need to use an extra eval for that.

    Hope it helps,