简体   繁体   English

迭代两个列表并从第一个列表中设置元素

[英]Iterate over two list and set element from first list

I have two ArrayList as below -我有两个ArrayList如下 -

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

promotions list size is not confirm but certificates list size is confirmed. promotions列表大小未确认,但certificates列表大小已确认。 So consider first list size is 2 and second list size is 3所以考虑第一个列表大小为 2,第二个列表大小为 3

I want to set promotionCode in second list from certificates but in second list some time promotionCode is not present.我想在certificates的第二个列表中设置promotionCode ,但在第二个列表中某些时候promotionCode不存在。

for (int i = 0; i < getCertificateNumber().size(); i++) {
   if (!promotions().isEmpty()) {
       promotions().get(i).setPromotionCode(getCertificateNumber().get(i));
   }
}

as in above for loop it set only first two promotions in promotion list because certificate list size two与上面for loop一样,它仅在promotion list中设置了前两个促销,因为certificate list大小为 2

How can I avoid any element from second list which don't have promotionCode and set CERT to element which has promotionCode如何避免第二个列表中没有promotionCode的任何元素并将CERT 设置为具有promotionCode的元素

You can add an if statement to check if the promotion code is not null, in this way to avoid getting beyong CERT1:您可以添加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
 }
}

This code will filter out promotions without codes and limit it to the number of certs we have.此代码将过滤掉没有代码的促销活动,并将其限制为我们拥有的证书数量。 Then you can run your for loop to map the codes to valid promotions.然后你可以运行你的 for 循环到 map 代码到有效的促销。 Also, in this case I would run the for loop over validPromotions , not certificates , because we might not have any valid promotions.此外,在这种情况下,我会在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM