Правило
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
функция накопления
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)));
}
}
тестовый вывод
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}
теория