本文将分享几个遍历map集合的方法。
最近遇到个蛋疼的事情,《Drools7中Map类型数据源操作》一文中提到“本文介绍了Map类的数据源在drools的condition部分遍历的方法。”,然后示例中写的是从工作内存中带有条件的遍历Map类型实例,有人质疑这文章与大纲不符,示例不是写的遍历。什么叫遍历,在我看来遍历直白点不就是循环查询嘛,循环查询集合叫遍历,加了个条件筛选,循环查询内存就不是遍历?抬杠!
进入正题!!!
说明一下:以下drl部分代码使用设置为java类型,纯属为了好看,实际遵循DRL文件语法规则。
数据源准备
public static void main(String[] args) {
KieServices kieServices = KieServices.Factory.get();
KieContainer kieContainer = kieServices.getKieClasspathContainer();
KieSession kieSession = kieContainer.newKieSession();
Map map = new HashMap();
map.put("first",1);
map.put("second",2);
map.put("third",3);
Map map1 = new HashMap();
map1.put("fourth",4);
map1.put("fifth",5);
//工作内存中插入两个map实例
kieSession.insert(map);
kieSession.insert(map1);
kieSession.fireAllRules();
kieSession.dispose();
}
一、基本写法(when中条件筛选,then中遍历)
1.drl如下:
rule "map_0"
when
//$m:Map(this['first'] == 1) //有条件的遍历查询工作内存中所有map实例
$m:Map()//遍历查询查询工作内存中所有map实例
then
//逐个遍历map实例的键值对
Set<Map.Entry> entries = $m.entrySet();
System.out.println("===========begin===========");
for(Map.Entry entry : entries){
String key = (String) entry.getKey();
Integer