Search code examples
javaarraylisthashmapdrools

How to compare and set exact collection in java and drools?


I have a java class as below

public  class Ball 
{
  private int size;
  private String brand;
  private ArrayList<String> colour;
  private HashMap<String, String> price;

  //getter and setters

}

I want to create Drools rule (java dialect) to read the size, brand and colour and set price map accordingly.

colour ArrayList should match exact e.g. if a ball has Red, Black & Blue colour together, then a particular rule should apply.

price map e.g. [{"US", "1.79"},{"UK", "1.48"},{"UAE", "11.37"}]. Don't confuse this with json, it is a java HashMap.

rule "rule 1"
when
ball : Ball
(
 size == 14,
 brand ==  "NIVIA",
 colour ==  //here i want to compare exact match of the arraylist.
)
then
 ball.setPrice(//here i want to set price map);
end

Please help to create the .drl file


Solution

  • First of all, we should question the use of a List<String> for holding a number of colours. Is order really important? It's possible that you want to distinguish a red ball with green and blue dots from a white ball with purple stripes, but even so "order" alone won't be able to express all subtleties. Point is, List.equals (and also == in Drools) is defined to return true if and only if elements are equal, one by one.

    The same problem arises if you use a String[] and call Arrays.equals().

    I think the best solution would be to use a

    private Set<String> colour;
    

    and write the rule as

    rule "rule 1"
    when
        ball: Ball( size == 14, brand ==  "NIVIA",
                    colour == new HashSet( Arrays.asList("Red", "Black", "Blue") ) )
    then
        ball.setPrice(...);
    end
    

    Your Java application might provide a Ball method:

    public boolean hasColours( String... colours )
    

    which would simplify the notation in the rule:

      ball: Ball( size == 14, brand ==  "NIVIA",
                  ball.hasColours("Red", "Black", "Blue") )