【问题标题】:How to set value inside nested forEach() in java8?如何在 java8 的嵌套 forEach() 中设置值?
【发布时间】:2019-05-20 15:46:52
【问题描述】:

我有一种情况,我正在迭代List<DiscountClass>,并且需要根据满足条件将列表值与另一个List<TypeCode> 进行比较(当Discount.code 等于TypeCode.code)我需要设置@987654325 @。如何在 java 8 中使用嵌套的 forEach 循环来实现这一点? (比较java 8 forEach中的值后我无法设置)。

for (Discount dis : discountList) {
    for (TypeCode code : typeCodeList) {
        if (dis.getCode().equals(code.getCode())) {
            dis.setCodeDesc(code.getCodeDesc());
        }
    }
}

【问题讨论】:

  • 什么是po,什么是b
  • 抱歉,现在已编辑。
  • 您的TypeCode 理想情况下应该是一个带有desc 字段的枚举。即使是Map 也会比TypeCodes 的列表更好。

标签: foreach java-8 stream


【解决方案1】:

使用 java 8 lambda 的可能解决方案如下所示:

    discountList.forEach(dis -> {
        typeCodeList
          .stream()
          .filter(code -> dis.getCode().equals(code.getCode()))
          .findAny()
          .ifPresent(code -> dis.setCodeDesc(code.getCodeDesc()));
    });

对于每个折扣,您根据代码过滤 TypeCode,如果找到任何类型代码,则将 desc poperty 设置为找到的 TypeCode。

【讨论】:

    【解决方案2】:

    另一个答案显示了如何将嵌套循环转换为嵌套函数循环。
    但与其遍历TypeCode 的列表,不如使用HashMap 来获得随机访问,或者像这样的枚举:

    public enum TypeCode {
        CODE_1("description of code 1"),
        CODE_2("description of code 2");
    
        private String desc;
    
        TypeCode(String desc) {
            this.desc = desc;
        }
    
        public String getDesc() {
            return desc;
        }
    }
    
    public class Discount {
    
        private String typeCode; //assuming you can't have the type as TypeCode
        private String desc;
    
        public Discount(String typeCode) {
            this.typeCode = typeCode;
        }
    
        //getters/setters
    }
    

    那么你的代码会变成:

    Discount d1 = new Discount("CODE_1");
    Discount d2 = new Discount("CODE_2");
    
    List<Discount> discounts = List.of(d1, d2);
    discounts.forEach(discount ->
            discount.setDesc(TypeCode.valueOf(discount.getTypeCode()).getDesc()));
    

    【讨论】:

    • 这适用于Hashmap,在我的情况下我使用列表(当然我可以保留为hashmap),但要求是保留为列表。感谢您的解决方案:)
    猜你喜欢
    • 2015-12-07
    • 1970-01-01
    • 2020-05-02
    • 2020-05-01
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 2020-12-02
    相关资源
    最近更新 更多