我遇到一种情况,我要迭代List<DiscountClass>
,并且需要根据满足条件的条件(当List<TypeCode>
等于{{1}时,将列表值与另一个Discount.code
进行比较。 })我需要设置TypeCode.code
。如何在Java 8中使用嵌套的forEach循环实现此目标? (比较Java 8 forEach中的值后,我无法设置。)
Discount.setCodeDescr()
答案 0 :(得分:3)
使用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之一。
答案 1 :(得分:1)
另一个答案显示了如何将嵌套循环转换为嵌套功能循环。
但是,与其遍历Object.defineProperty(Promise.prototype, "state", {
get: function(){
const o = {};
return Promise.race([this, o]).then(
v => v === o ? "pending" : "resolved",
() => "rejected");
}
});
// usage:
(async () => {
console.log(await <Your Promise>.state);
console.log(await Promise.resolve(2).state); // "resolved"
console.log(await Promise.reject(0).state); // "rejected"
console.log(await new Promise(()=>{}).state); // "pending"
});
的列表,不如使用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
}