亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java 8中通過多個匹配值獲取列表的對象

Java 8中通過多個匹配值獲取列表的對象

米琪卡哇伊 2022-05-21 13:52:19
我正在嘗試按最高值匹配進行規則過濾。我有一個包含多個產品的銷售,我必須對每個產品應用不同的規則。獲得此結果的最佳方法是什么?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)));



查看完整回答
反對 回復 2022-05-21
  • 1 回答
  • 0 關注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號