droolskiedrools-guvnordrools-kie-server

Applying accumulate on subclass in drools


I am creating the object of stock and inserting stock values as below

  1. Customer 1 has 2 stocks stocks4 and stocks5
  2. customer2 has 1 stocks arrayListStocks1

Here I am trying to make sum of all Stocks for given session

Stocks stocks1=new Stocks("stock1", 1, 1);
            Stocks stocks2=new Stocks("stock2", 2, 2);

            Stocks stocks4=new Stocks("stock4", 4, 4);
            Stocks stocks5=new Stocks("stock5", 5, 5);

            ArrayList<Stocks> arrayListStocks1=new ArrayList<Stocks>();
            arrayListStocks1.add(stocks1);
            arrayListStocks1.add(stocks2);


            Customer customer1= new  Customer();
            customer1.setCustomerName("ACC");
            customer1.setStocks(arrayListStocks1);

            ArrayList<Stocks> arrayListStocks2=new ArrayList<Stocks>();
            arrayListStocks2.add(stocks4);
            arrayListStocks2.add(stocks5);


            Customer customer2= new  Customer();
            customer2.setCustomerName("JINDAL");
            customer2.setStocks(arrayListStocks2);

            kSession.insert(customer1);
            kSession.insert(customer2);


rule "Rule5"
 // agenda-group "promotions2"
dialect "java"
no-loop
salience 80
    when
         $list: List() from collect($customer:Customer($customerName:customerName,$stk:stocks))
         $customer:Customer($customerName:customerName,$stk:stocks)
         $stocks:Stocks() from $stk
         $listStocks: List() from collect(Stocks($stockNumber:stockNumber > 1) from $stk )
         $sum:Number() from accumulate (Stocks($stockNumber: stockNumber) from $stk,sum($stockNumber))
    then
       // System.out.println("Rule5 Stock Number- " + $stocks.getStockNumber());
       // System.out.println("Rule5  SIZE - " + $listStocks.size());
        System.out.println("Number - " +  $sum);
end

when I run above rule I am getting below output Number - 9.0 Number - 9.0 Number - 3.0 Number - 3.0

how to calculate sum of 2 stocks from customer1 and customer2 I am expecting the result 12

Thanks,


Solution

  • If all you want to do is to calculate the sum of all the stock for all the customers, then you can try something like this:

    rule "Stocks Sum"
    when
      $n: Number() from accumulate(
        Customer($stk:stocks) and
        Stocks($stockNumber: stockNumber) from $stk,
        sum($stockNumber)
      )
    then
      //...
    end
    

    Hope it helps