Search code examples
drools

How to get a value from a map inside a map in drools


I have a Main map object inside it contains another map. Now i need to get the value from it in drools? My code looks like

HashMap<String,Object> studentsMap = new HashMap<String,Object>();
HashMap<String,int> marksMap = new HashMap<String,int>();
marksMap.put("Maths",98);
marksMap.put("Chemistry",96);
studentsMap.put("JohnDoe", marksMap);

I am inserting this 'studentsMap' object to the drools session and firing the rules. How to compare marks values in drools (How to check condition if mark is greater than 90)?


Solution

  • The proposed solutions did not worked for me.

    You need to call map differently in eval.

    rule "studentsMap"
    
    when
      Student($marks : markMap)
      eval((int)$marks.get("Maths") > 90)
     then
      System.out.println("mark greater than 90");
    end
    

    Also additional casting should be done.

    Links: http://lists.jboss.org/pipermail/rules-users/2007-November/003921.html

    UPD: Found more conventional way to do this

    rule "studentsMap"
    
    when
      $student: Student($marks : markMap, $marks.get("Maths") > 90)
     then
      System.out.println("mark greater than 90");
    end
    

    You can also perform check for key presence in the map before calling get.

      $student: Student($marks : markMap, $marks.containsKey("Maths"), $marks.get("Maths") > 90)