在Java 8中通过多个匹配值获取列表的对象

时间:2019-01-24 12:57:36

标签: java performance

我正在尝试根据最高值进行过滤。

我的销售中包含几种产品,因此我必须对每种产品应用不同的规则。

获得此结果的最佳方法是什么?

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 个答案:

答案 0 :(得分:0)

首先,我将所有四个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)));