dhruv dar
dhruv dar

Reputation: 11

Drools Converting list of one object to list of another object in drools

I have a class say A with list of Waiver objects and I want to iterate this list, convert it into list of WaiverInfo objects and insert to object of class B type . Is it possible to achieve this in drools ?

class A {
    List<Waiver> waivers;
}

class B {
    List<WaiverInfo> waiverList;
}

class Waiver {
    String code;
    String name;
}

class WaiverInfo {
    String code;
    String name
}

Upvotes: 0

Views: 374

Answers (1)

Roddy of the Frozen Peas
Roddy of the Frozen Peas

Reputation: 15190

Well, sure this is possible and not particularly difficult.

I'm going to assume that you insert 'A' into the rules, and want to write rules against 'B'. I will also assume that you're not going to insert any 'B' at all into the rules.

rule "Convert A to B"
when
  not( B() )
  $a: A()
then
  B b = new B();
  // do the conversion here in regular java
  insert(b);
end

rule "Example - do something with B"
when
  B( $waiverList: waiverList )
then
  // ...
end

Basically the conversion rule checks that there's no B present in the working memory, but there is an A. If those conditions are met, the conversion happens in the "then" and the result is inserted into working memory.

The second rule will then fire because there is a B present in working memory after insert in the first rule triggers the reevaluation of subsequent rules.

Note that this conversion rule only works if there is only 1 'A' present in working memory. If you have 2 'A' instances, the first one will trigger the rule and convert and insert a 'B'. At that point, the conversion rule will no longer be valid to fire, so it will not ever convert the second 'A' instance.

If you do have multiple instances of A, there's a bunch of ways you could address this. For example, you could retract each A after converting it. But the example above is generally how you'd do it.

Upvotes: 1

Related Questions