遍历两个列表并从第一个列表设置元素

时间:2020-05-29 00:06:12

标签: java java-8

我有两个ArrayList如下-

certificates=[CERT1, CERT2]
promotions=[{type}, {type, promotionCode}, {type, promotionCode}]

promotions列表大小未确认,但certificates列表大小已确认。因此,请考虑第一个列表大小为2,第二个列表大小为3

我想在promotionCode的第二个列表中设置certificates,但是有时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的尺寸为两个

如何避免第二个列表中没有promotionCode的元素并将CERT设置为具有promotionCode的元素

2 个答案:

答案 0 :(得分:0)

您可以添加一个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
 }
}

答案 1 :(得分:0)

此代码将过滤掉没有代码的促销活动,并将其限制为我们拥有的证书数量。然后,您可以运行for循环以将代码映射到有效的促销中。另外,在这种情况下,我会在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());
相关问题