我正在嘗試按最高值匹配進行規則過濾。我有一個包含多個產品的銷售,我必須對每個產品應用不同的規則。獲得此結果的最佳方法是什么?List<Rule> rules = listOfRules();String system = "MySystem1";Map<Product, Rule> mapOfProductRule = new HashMap<Product, Rule>();sale.getProducts().forEach(product -> { int points = 0; Rule matchedRule = null; for (Rule rule : rules) { if (system == rule.getSystem()) { int countMatchs = 0; if (sale.getValue1() == rule.getValue1()) countMatchs++; if (sale.getValue2() == rule.getValue2()) countMatchs++; if (product.getPvalue1() == rule.getPvalue1()) countMatchs++; if (product.getPvalue2() == rule.getPvalue2()) countMatchs++; if (countMatchs!= 0 && points < countMatchs) { points = countMatchs; matchedRule = rule; } } } mapOfProductRule.put(product, matchedRule);});return mapOfProductRule;
1 回答

德瑪西亞99
TA貢獻1770條經驗 獲得超3個贊
首先,我會將所有 4 if.. 移動到Rule類中的一個方法中
public int getScore(Sale sale, Product product) {
int count = 0;
if (this.getValue1() == sale.getValue1()) count++;
//...
return count;
}
然后我會rules用
Rule bestRule = rules.stream().max(Comparator.comparingInt(r -> r.getScore(sale, product)));
添加回答
舉報
0/150
提交
取消