Search code examples
javadrools

Check for specific element in a map in Drools


I want to access map key and compare to value that contains or not.

//The Attribute class contains one map in the form of key and multiple values

public class Attribute {
    private Map<String, List<String>> mapAttribute;

    public Map<String, List<String>> getMapAttribute() {
        return mapAttribute;
    }

    public void setMapAttribute(Map<String, List<String>> mapAttribute) {
        this.mapAttribute = mapAttribute;
    } 
}

 public class DroolsMain {

        public static Attribute attribute = new Attribute();

        public static void main(String[] args) throws DroolsParserException, IOException {

        Map<String, List<String>> map = new HashMap<String, List<String>>();  

        List<String> listSubject = new ArrayList<String>(); 
        listSubject.add("email1");
        listSubject.add("email2");
        map.put("Subject", listSubject);

        List<String> listFrom = new ArrayList<String>(); 
        listFrom.add("Sathish Kumar");
        map.put("From", listFrom);

        attribute.setMapAttribute(map);
    }
//...
workingMemory.insert(attribute);
}

Rules.drl

rule "Get Subject key: with particular value"  
   when
        attribute : Attribute($mapAttribute : mapAttribute) 
       //I want to compare value of **"Subject"**  
        List( this.contains( "email1")) from $mapAttribute.get("Subject")

     then
        System.out.println("Rule run successfully Getting key with particular value");

    end

I didn't get the value in Rule.drl. It shows not match any rule. so please help to find the value.


Solution

  • The list contains "email1" and "email2" but you are checking for "email".

    But the rule would have to be written as

    rule "Get Subject key: with particular value"  
    when
        attribute : Attribute($mapAttribute : mapAttribute)  
         $values : String( this == "email1" ) from $mapAttribute.get("Subject")
    then ... end
    

    If the result of a 'from' is a List, it is automagically unravelled. This is useful, but occasionally surprising. (What if you need the entire list?)