我试图使Predicate
为了知道我是 已完成某些记录,但我需要一个可能随时更新的记录的外部列表;我也需要跟踪我已经处理的那些。称为lambda表达式,但取决于“外部”参数
这是怎样的代码看起来像:
// This one is at class level and gets updated in different places
Set<String> recipients ...
private void method(Iterable<CustomType> records) {
final Set<String> doneWith = new HashSet<>();
try {
someService.doThis(records, record -> { // records is a list of CustomType
boolean notify = Stream.of(doneWith, recipients)
.noneMatch(s -> s.contains(record.getField()));
if (notify) {
doneWith.add(record.getField());
}
return notify;
});
recipients.addAll(doneWith);
} catch (Exception e) {
// TODO: Do something here
}
}
...现在我要“外化”为Predicate
第二个参数someService.doThis(records, <this_one>
。任何线索?
这是呼叫的类型:
public void doThis(Iterable<CustomType> records, Predicate<CustomType> notify) {
records.forEach(r -> {
// Do some stuff here
if (notify.test(r)) {
// Do some more stuff here
}
});
}
注:主要原因希望能够重用是因为我可能需要在别处的谓语,但截至目前,它也使用在测试案例中。
呃,这是什么部分是'Predicate'?而谓词确实不应该修改外部状态,就像你在'doneWith'中做的那样。但是你真正需要做的只是返回一个返回一个'Predicate'的方法,并从中返回这个lambda。 –
所以你的意思是说''使用'doneWith'不应该在'Predicate'中完成? –
是的,我的意思是说。 –