使用收集在流口水中获取相似的对象 [英] Using collect in drools to get similar objects
问题描述
我试图在Drools中收集一些对象,但是我只想收集具有相同属性的对象。假设有一个TestData类:
I am trying to collect some objects in Drools, but I want to only collect objects which have the same attribute. To wit, imagine a TestData class:
public class TestData {
int number;
String name;
//Getters, setters, rest of class
}
我想使用collect获取具有相同名称的所有TestData。对于以下数据集,我想要一个规则,该规则可以将前两个(都具有名称 Test1)和后两个( Test2)作为单独的集合进行收集。
I want to use collect to get all TestDatas which have the same name. For the following data set, I want a rule which can collect the first two (both having the name 'Test1') and the second two ('Test2') as separate collections.
custom.package.TestData< number: 1, name:'Test1' >
custom.package.TestData< number: 2, name:'Test1' >
custom.package.TestData< number: 3, name:'Test2' >
custom.package.TestData< number: 4, name:'Test2' >
类似
rule "Test Rule"
when
$matchingTestDatas : ArrayList( size > 1 ) from collect ( TestData( *magic* ) )
then
//Code
end
但是很明显,如果没有魔术,那将无法工作-它使我具有每个名称的所有TestData条目的数组。我可以将其用作规则的基础,并在右侧进行扩展处理,以遍历所有测试数据条目,但感觉像是在流口水中应该有足够聪明的东西可以匹配这种方式。
But obviously that won't work without the magic- it gets me an array of all the TestData entries with every name. I can use that as the basis for a rule, and do extended processing in the right hand side iterating over all the test data entries, but it feels like there should be something in drools which is smart enough to match this way.
推荐答案
大概魔术就是:
TestData( name == 'Test1' )
或
TestData( name == 'Test2' )
...用于每个集合。但这似乎太明显了。我是否遗漏了某些东西?
... for each of the collections. But that seems too obvious. Am I missing something?
根据OP在对此答案的评论中的澄清,看来是 Map
的集合是必需的,从名称键入。为此,需要 accumulation
,而不是 collect
。
Based on the clarification from the OP in the comments on this answer, it would appear that a Map
of collections is required, keyed from the name. To support this, accumulate
is required, rather than collect
.
$tests: HashMap()
from accumulate( $test : TestData( name == $name ),
init( HashMap tests = new HashMap(); ),
action(
if (tests.get($name) == null) tests.put($name, new ArrayList();
tests.get($name).add($test);
),
reverse(
tests.get($name).remove($test);
),
result( tests )
);
这篇关于使用收集在流口水中获取相似的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!