将一个(标签)列表与另一个列表匹配,并检测公共元素的存在 [英] Matching a list (of tags) with another and detecting presence of common elements
问题描述
我的要求是匹配标签.在示例中,该特定的HourConstraint
检查分配给Hour(23)
的TeacherHour
.
My requirement is to match tags. In the example, this particular HourConstraint
checks the TeacherHour
assigned to Hour(23)
.
具体来说,它将检查TeacherHour.attributes["tags"]
中的值["asst_ct","teacher_john_smith"]
和至少检测到一个匹配,在这种情况下为两个("asst_ct"
和"teacher_john_smith"
).
Specifically, it checks TeacherHour.attributes["tags"]
for the values ["asst_ct","teacher_john_smith"]
and detects atleast one match, two in this case (both "asst_ct"
and "teacher_john_smith"
) .
TeacherHour:
id: 47
assigned_hour: Null
attributes:Map<List<String>>
"tags":["asst_ct","no_strenuous_duties","kinda_boring","teacher_john_smith"]
"another_attribute":[...]
HourConstraint:
hour: Hour(23)
attribute: "tags"
values_list: ["asst_ct","teacher_john_smith"]
问题:如何检测两个列表之间是否存在(常见元素)?
Question: How do I detect the presence (true or false) of common elements between two lists?
Drools Expert具有memberOf
和contains
,但是它们检查标量与集合,而不是集合与集合.
Drools Expert has memberOf
and contains
, but they check a scalar vs a collection, never a collection vs a collection.
我看到了两种可能的方式:
I see two potential ways:
- 引入一个函数
boolean isIntersecting(list,list)
并告诉Drools使用该函数进行真理检查 - 将
TeacherHour.attributes[]
作为字符串而不是列表,并将HourConstraint.valueslist
作为可与该列表匹配的正则表达式
- introduce a function
boolean isIntersecting(list,list)
and tell Drools to use that for truth checking - Implement
TeacherHour.attributes[]
as a string instead of a list andHourConstraint.valueslist
as a regular expression that can match that list
推荐答案
有一些选择.最直接的方法是使用Collections类为您做到这一点:
There are a few options. Most straight forward is to use the Collections class to do that for you:
rule X
when
$t: TeacherHour( )
HourConstraint( Collections.disjoint( $t.attributes["tags"], values_list ) == false )
...
如果这是您经常在规则中使用的东西,那么我建议将该函数包装在Drools支持的可插入运算符中.假设您将运算符命名为"intersect",然后可以这样编写规则:
If this is something you would use often in your rules, then I recommend wrapping that function in a pluggable operator, supported by Drools. Lets say you name the operator "intersect", you can then write your rules like this:
rule X
when
$t: TeacherHour( )
HourConstraint( values_list intersect $t.attributes["tags"] )
...
第三个选项是使用"from",但是在运行时效率较低,因为它会导致第一个列表上的迭代:
A third option, is to use "from", but that is less efficient in runtime as it causes iterations on the first list:
rule X
when
$t: TeacherHour( )
$tag : String() from $t.attributes["tags"]
exists( HourConstraint( values_list contains $tag ) )
...
这篇关于将一个(标签)列表与另一个列表匹配,并检测公共元素的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!