英文:
Why same object passes to lambda when applied in a loop?
问题
我有一个对象列表,如 Collection<Cashflow> cashflows = cashflowDao.findAll();
。然后我在 for 循环中对列表进行迭代,并根据条件执行一些操作。
for(Cashflow cashflow: cashflows) {
Condition condition = ruleService.getSTPCondition(cashflow, "NON-STP", "Counterparty STP Rule");
Rule stpRules = getRule(cashflowDao, cashflow, condition);
rules.register(stpRules);
rulesEngine.fire(rules, facts);
}
getRule()
的实现如下:
private Rule getRule(CashflowDao cashflowDao, Cashflow cashflow, Condition condition) {
System.out.println("Cashflow to evaluate:" + cashflow.getId()); //现金流 id 是唯一的。
return new RuleBuilder().when(condition).then(new Action() {
@Override
public void execute(Facts facts) throws Exception {
//传递给这里的现金流是列表中的同一个旧/第一个现金流对象。
System.out.println("Cashflow Id to Load: " + cashflow.getId());
}
}).build();
}
在 execute()
方法中,列表中的第一个现金流对象 总是被传递,无论对象的当前值如何。如何将唯一的现金流对象实例传递给 execute()
?如果我有三个 id 为 97、98、99 的现金流,输出将会是:
Cashflow to evaluate:97
Cashflow Id to Load: 97
Cashflow to evaluate:98
Cashflow Id to Load: 97
Cashflow to evaluate:99
Cashflow Id to Load: 97
英文:
I've a list of objects as Collection<Cashflow> cashflows = cashflowDao.findAll();
. I then iterate over the list in a for loop and apply some action based on condition.
for(Cashflow cashflow: cashflows) {
Condition condition = ruleService.getSTPCondition(cashflow, "NON-STP", "Counterparty STP Rule");
Rule stpRules = getRule(cashflowDao, cashflow, condition);
rules.register(stpRules);
rulesEngine.fire(rules, facts);
}
The getRule()
implementation is:
private Rule getRule(CashflowDao cashflowDao, Cashflow cashflow, Condition condition) {
System.out.println("Cashflow to evaluate:" + cashflow.getId()); //The cashflow id is unique.
return new RuleBuilder().when(condition).then(new Action() {
@Override
public void execute(Facts facts) throws Exception {
//The cashflow is the same old/first cashflow object in the list gets passed here.
System.out.println("Cashflow Id to Load: " + cashflow.getId());
}
}).build();
}
In the execute()
method the first cashflow in the list is always passed no matter what the current value of the object is. How can I pass the unique instance of cashflow object to execute()
? If I have three cashflows with ids 97,98,99, the output is:
Cashflow to evaluate:97
Cashflow Id to Load: 97
Cashflow to evaluate:98
Cashflow Id to Load: 97
Cashflow to evaluate:99
Cashflow Id to Load: 97
专注分享java语言的经验与见解,让所有开发者获益!
评论