繁体   English   中英

在drools-java中收集为哈希/映射键值对

[英]Collect as a hash/map key-value pair in drools-java

我正在尝试在drools中收集一些项目作为键值对,但是我无法修改现有的java代码,我必须通过drools中的规则来执行此操作规则是这样的:

    **when** 
// I know it's collected as a list, but this is what I want to modify in my code and I don;t know how
    $myList : List() from accumulate(MyClass($myclassId: id,
                                             $myClassValue : value), collectList($$myclassId + " " + $myClassValue))

我想在 then 子句中将其用作 hash,我知道这是一个列表,但我不知道将其收集为 hash 以将其用作哈希 [id] -> 值的语法。

规则

import java.util.List;
import java.util.Map;
import java.util.AbstractMap.SimpleEntry;
import accumulate org.droolsassert.MapAccumalateFunction collectMap;

rule X
    when
        $list: List()
        $numberTypes: Map() from accumulate (
            $elem: Number() from $list,
            collectMap(new SimpleEntry($elem.intValue(), $elem.getClass()))
        )
    then
        System.out.println('collected: ' + $numberTypes);
end

累积 function

public class MapAccumalateFunction implements AccumulateFunction<HashMap<Object, Object>> {

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    }

    @Override
    public HashMap<Object, Object> createContext() {
        return new HashMap<>();
    }

    @Override
    public void init(HashMap<Object, Object> context) throws Exception {
    }

    @Override
    public void accumulate(HashMap<Object, Object> context, Object value) {
        Entry<Object, Object> entry = (Entry<Object, Object>) value;
        context.put(entry.getKey(), entry.getValue());
    }

    @Override
    public void reverse(HashMap<Object, Object> context, Object value) throws Exception {
    }

    @Override
    public Object getResult(HashMap<Object, Object> context) throws Exception {
        return context;
    }

    @Override
    public boolean supportsReverse() {
        return false;
    }

    @Override
    public Class<?> getResultType() {
        return null;
    }
}

测试

@DroolsSession(resources = "classpath:/test.drl")
public class PlaygroundTest {

    @Rule
    public DroolsAssert drools = new DroolsAssert();

    @Test
    public void testIt() {
        drools.insertAndFire(asList(new Integer(1), new AtomicInteger(2), new BigDecimal(3)));
    }
}

测试 output

00:00:00 --> inserted: Arrays.ArrayList[a={1,2,3}]
00:00:00 --> fireAllRules
00:00:00 <-- 'X' has been activated by the tuple [ArrayList, HashMap]
collected: {1=class java.lang.Integer, 2=class java.util.concurrent.atomic.AtomicInteger, 3=class java.math.BigDecimal}

理论

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM