How to compute the percentage of Vs in a list with drools rules. In case of percentage of V are 80%, then fire a drools rule.
I have a ArrayList that will have only two values: V and N.
List<String> list = new ArrayList<>();
How to count the number of V with drools rules, every V and N will worth 1, get total sum sum of V and N.
In java
Map<String, Long> counted = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("Counted: "+counted);
The expression above prints
Counted: {V=4, N=15}
After get the the values, there will be an drols rule expression, which in case of 80 % occurrence the count V appearance prints "ok" otherwise prints not allowed.
Here is a rule that computes the percentage of Vs in the list:
rule "countVN"
when
$vn: ArrayList( $s: size )
accumulate( String( toString == "V" ) from $vn;
$cnt: count( 1 );
$cnt.doubleValue()/$s >= 0.8 )
then
System.out.println( "80% or more" );
end
This fires just for the >= 80% case. If you need a result in any case, use
...
accumulate( String( toString == "V" ) from $vn;
$cnt: count( 1 ))
then
if( $cnt.doubleValue()/$s >= 0.8 ) ...