英文:
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循环
中,它仅设置了promotion列表
中的前两个促销,因为certificate列表
的大小为两个。
如何避免第二个列表中没有promotionCode
的任何元素,并将CERT
设置为具有promotionCode
的元素。
英文:
I have two ArrayList
as below -
certificates=[CERT1, CERT2]
promotions=[{type}, {type, promotionCode}, {type, promotionCode}]
promotions
list size is not confirm but certificates
list size is confirmed. So consider first list size is 2 and second list size is 3
I want to set promotionCode
in second list from certificates
but in second list some time promotionCode
is not present.
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
How can I avoid any element from second list which don't have promotionCode
and set CERT to element which has promotionCode
答案1
得分: 0
你可以添加一个if语句来检查促销代码是否不为空,以此方式避免超出CERT1:
int i = 0;
for (Promotion prom : promotions) {
// 检查促销代码是否不为空
if (prom.getPromotionCode() != null) {
prom.setPromotionCode(getCertificateNumber().get(i));
i++; // 仅在不为空时增加
}
}
英文:
You can add an if statement to check if the promotion code is not null , in this way to avoid getting beyong 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
}
}
答案2
得分: 0
这段代码将筛选出没有代码的促销活动,并将其限制为我们拥有的证书数量。然后,您可以运行 for 循环将代码映射到有效的促销活动。此外,在这种情况下,我会在 validPromotions
上运行 for 循环,而不是在 certificates
上运行,因为我们可能没有任何有效的促销活动。
List<Promotion> validPromotions = promotions.stream()
.filter(x -> x.promotionCode != null) // 只保留具有有效促销代码的促销活动
.limit(certificates.length) // 保留与我们拥有的证书数量相同的促销活动
.collect(Collectors.toList());
英文:
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. Also, in this case I would run the for loop over validPromotions
, not certificates
, because we might not have any valid promotions.
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());
专注分享java语言的经验与见解,让所有开发者获益!
评论