Search code examples
drools

Drools - How to get String[] from ArrayList collect


rule "Your First Rule"
no-loop
salience 10
when
    $c : Company()
    // $e : String()
    $e : StaffException()
    $r : StaffExcCode( $r.getCode() == "1" ) from $e.getStaffException()
    $y : ArrayList()
         from collect ( String() from $r.getStaffExc())
      $ee : Staff( StaffCode not memberOf( $y )) from $c.getStaffInfo()

then
    //actions
   System.out.println("Satisfied." + $y);
    //System.out.println("Satisfied." + $ee);

end

I got an arrayList $y and hoping to generate an String[] array to use as the condition in the memberOf. How it can be done for realize this transformation?

This is the Class used in the demo: Class StaffExcCode:

public class StaffExcCode {
    private String StaffExc;
    private String code;

    public StaffExcCode(String StaffExc, String code) {
        this.StaffExc = StaffExc;
        this.code = code;
    }
    /* ignore the get and set */
}

Class StaffException:

public class StaffException {
    private List<StaffExcCode> exc;
    /* ignore the get and set */
}

Class Staff:

public class Staff {
    private String StaffCode;

    private String StaffName;

    private int StaffAge;
    /* ignore the get and set */
}

Class Company:

public class Company {
    private int CompanyCode;

    private String CompanyName;

    private int StaffNumber;

    private List<Staff> StaffInfo;
    /* ignore the get and set */
}

Solution

  • I'm not sure whether I got it right as you haven't posted a statement what the rule should do or (even better) a data set with the expected results. (If you stick to the usual JavaBeans convention, the exc in StaffException doesn't match $e.getStaffException().)

    I don't think you have to collect the data into a list; there is the not CE which can be applied to a pattern

    rule "Your First Rule"
    when
      $c : Company( $si: staffInfo )
      $staff: Staff( $staffCode: staffCode, $sn: staffName ) from $si
      StaffException( $exc: exc )
      not StaffExcCode( staffExc == $staffCode, code == "1" ) from $exc
    then
       System.out.println("Satisfied: " + $sn);
    end
    

    It would be even simpler if you'd insert Staff and StaffExcCode as facts, rather than extract them from the containing fact objects.