Search code examples
drools

Breaking from inside a collect in Drools


I'm new to Drools, so I apologize if this is basic. But how do I break in the middle of a collect? For example, in the following code

 c : Customer()
items : List( size == c.items.size ) 
      from collect( Item( price > 10 ) from c.items )

This code checks if all items have a price > 10. But if I want to see if any of the items have a price > 10, what do I do? I can change code to size > 0 instead of size == c.items.size, but that would still mean the collect iterates through all the items. Is it possible to break if any of the items match the condition from within the collect?


Solution

  • If you just want to check for existence, then you can use the exists operator:

    rule "Sample"
      c : Customer()
      exists Item( price > 10 ) from c.items
    then
      //...
    end
    

    In this case, you don't even need to use a collect. The from keyword will "loop" over all of the items in the collection.

    You can check the Drools' Manual for more information about this Conditional Element.

    Hope it helps,