地图迭代列表drools drl

时间:2017-05-23 09:01:42

标签: java drools

我正在尝试迭代地图列表,如下所示:

[
  {
    "endOffset": 2913,
    "coreference": "Tehran",
    "entity": "a country",
    "beginOffset": 2904
  },
  {
    "endOffset": 3055,
    "coreference": "Bashar al-Assad",
    "beginOffset": 3052
  },
  {
    "endOffset": 3130,
    "coreference": "Bashar",
    "beginOffset": 3128
  }
]

我正在执行的代码块如下:

PojoCorefList pojoCorefList=new PojoCorefList();
List<Map<String,String>> corefList=new ArrayList<Map<String,String>>();
Map<String,String> testMap=new LinkedHashMap<>();
testMap.put("beginOffset", "3052");
testMap.put("coreference", "Bashar al-Assad");
testMap.put("endOffset", "3055");
corefList.add(testMap);
Map<String,String> testMap2=new LinkedHashMap<>();
testMap2.put("beginOffset", "3130");
testMap2.put("coreference", "Bashar");
testMap2.put("endOffset", "3128");
corefList.add(testMap2);
Map<String,String> testMap3=new LinkedHashMap<>();
testMap3.put("beginOffset", "2913");
testMap3.put("coreference", "Tehran");
testMap3.put("endOffset", "2904");

corefList.add(testMap3);

pojoCorefList.setCityPlaces(corefList);
ksession.insert(pojoCorefList);

这是PojoCorefList类,如下所示:

public static class PojoCorefList {
    private List<Map<String,String>> cityPlaces;
    public List<Map<String,String>> getCityPlaces() {
         return cityPlaces;
    }

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

我试过的drl语法如下:

rule "List of Maps Testing"
    salience 1

    when
        $c : PojoCorefList($coref : cityPlaces)
    $item : List() from $coref
    entry : Entry() from $item.entrySet()
    //value: String() from entry.getValue()
    //Boolean(booleanValue :true) from value=="Tehran"

    then
      System.out.println("List Maps Testing: list is - "+$item);
end 

我相信,我正在迭代$ coref列表,现在我应该有一个地图,但如果我尝试从$ item获取entrySet(),我将获得如下异常:

Unable to Analyse Expression $item.entrySet():
[Error: unable to resolve method using strict-mode: java.util.List.entrySet()]
[Near : {... $item.entrySet() ....}]
                   ^ : [Rule name='List of Maps Testing']

2 个答案:

答案 0 :(得分:0)

Drools不了解泛型。但是,如果你提供正确的类,它应该工作。请注意from collection迭代集合。

  $c : PojoCorefList($coref : cityPlaces)
  $m : HashMap() from $coref  // cityPlaces are lists of Maps
  entry : Entry() from $m.entrySet()

或使用

  value : String() from $m.values()

(这可能取决于Drools版本。)

答案 1 :(得分:0)

如果您使用的是Drools 6.4及更高版本,也可以使用OOPath语法。它大大提高了LHS的紧凑性。

您的案例看起来就像这一个约束:

$ c:PojoCorefList($ entry:/ cityPlaces / entrySet)

其中$ entry的类型为Entry()。您可以在此处阅读有关OOPath的更多信息: https://docs.jboss.org/drools/release/6.5.0.Final/drools-docs/html/ch10.html#d0e13581