[英]Iterate over two list and set element from first list
我有两个ArrayList
如下 -
certificates=[CERT1, CERT2]
promotions=[{type}, {type, promotionCode}, {type, promotionCode}]
promotions
列表大小未确认,但certificates
列表大小已确认。 所以考虑第一个列表大小为 2,第二个列表大小为 3
我想在certificates
的第二个列表中设置promotionCode
,但在第二个列表中某些时候promotionCode
不存在。
for (int i = 0; i < getCertificateNumber().size(); i++) {
if (!promotions().isEmpty()) {
promotions().get(i).setPromotionCode(getCertificateNumber().get(i));
}
}
与上面for loop
一样,它仅在promotion list
中设置了前两个促销,因为certificate list
大小为 2
如何避免第二个列表中没有promotionCode
的任何元素并将CERT 设置为具有promotionCode
的元素
您可以添加if语句来检查促销代码是否不是null,这样可以避免超出CERT1:
int i = 0;
for ( Promotion prom : promotions ) {
// check if promotioncode is not null
if( prom.getPromotionCode() != null ) {
prom.setPromotionCode(getCertificateNumber().get(i));
i++; // increments only if not null
}
}
此代码将过滤掉没有代码的促销活动,并将其限制为我们拥有的证书数量。 然后你可以运行你的 for 循环到 map 代码到有效的促销。 此外,在这种情况下,我会在validPromotions
而不是certificates
上运行 for 循环,因为我们可能没有任何有效的促销活动。
List<Promotion> validPromotions = promotions.stream()
.filter(x -> x.promotionCode != null) // only keep promotions that have valid promotion codes
.limit(certificates.length) // only keep as many promotions as we have certificates for
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.