Получить объект списка с помощью нескольких соответствующих значений в Java 8 - PullRequest
0 голосов
/ 24 января 2019

Я пытаюсь сделать фильтрацию правил по совпадению по наибольшему значению.

У меня есть продажа, которая содержит несколько продуктов, и я должен применить к каждому продукту отдельное правило.

Как лучше всего получить этот результат?

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 голосов
/ 24 января 2019

Прежде всего, я бы переместил все 4, если .., в метод класса 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)));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...