Search code examples
javadrools

Drools get first element of List in where clause


Is it possible to get first element of list from when clause in Drools? If I don't know Object fields values inside the list and I want just to retrieve first element, how can I do this?

rule "TestRule1"
dialect "java"
when
    $c : Collection()
    $listCustObjs : ArrayList() from collect (CustomObject() from $c)

    $first : $listCustObjs.get(0) //<- something like this
    $otherObj : $first.other // <- take other element from first object from the list

then
   ...
end;

Solution

  • You need to cast the $listCustObjs object to List then only you will be able to use list methods. Casting is done in drools by using '#' operator. Check here.

    Also, you can directly use a statement like $first : $listCustObjs.get(0). In drools when all the computation or conditional check is done on Fact i.e object. So in your case, you can only get the value from $listCustObjs list when you will try to get it inside an object.