【发布时间】:2021-01-07 07:31:17
【问题描述】:
我有一个对象列表
OfferToCheck offer = new OfferToCheck();
offer.setDiscountId(null);
offer.setProductName("sadf spacefjkd");
offer.setServiceCode("dfsdfv");
offer.setServiceGroup("nospace");
OfferToCheck offer1 = new OfferToCheck();
offer1.setDiscountId("");
offer1.setProductName("sadfspacefjkd");
offer1.setServiceCode("sdnof");
offer1.setServiceGroup("sdf");
request.setOffersToCheck(Arrays.asList(offer,offer1));
request.setStartTrialPeriod("y");
if(service.validateStatus(request)){
System.out.println("true");
}
else{
System.out.println("false");
}
我想使用 java 8 流实现这个 for 循环
for(OfferToCheck offer : request.getOffersToCheck()){
if(offer.getDiscountId() != null && !offer.getProductName().isEmpty()){
if(!offer.getDiscountId().chars().allMatch(Character::isDigit)){
return isValid = false;
}
}
if(offer.getServiceCode() != null && !offer.getServiceCode().isEmpty()){
if(!offer.getServiceCode().chars().allMatch(Character::isAlphabetic)){
return isValid = false;
}
}
if(offer.getServiceGroup() != null && !offer.getServiceGroup().isEmpty()){
if(!offer.getServiceGroup().chars().allMatch(Character::isAlphabetic)){
return isValid = false;
}
}
if(offer.getProductName() != null && !offer.getProductName().isEmpty()){
if(!offer.getProductName().matches("[a-zA-Z ]*")){
return isValid = false;
}
}
}
我已经尝试过了,但是当 discountId 的值为空或 null 时,它不会将对象的其余部分包含到流中。
if(!request.getOffersToCheck().stream()
.filter(list -> (list.getServiceCode() != null && !list.getServiceCode().isEmpty()))
.filter (list -> list.getDiscountId() != null && !list.getDiscountId().isEmpty())
.filter (list -> list.getProductName() != null && !list.getProductName().isEmpty())
.filter (list -> list.getProductName() != null && !list.getProductName().isEmpty())
.filter (list -> list.getServiceGroup() != null && !list.getServiceGroup().isEmpty())
.allMatch(validateList -> (validateList .getDiscountId().chars().allMatch(Character::isLetterOrDigit)
&& validateList.getProductName().matches("[a-zA-Z0-9 ]*")
&& validateList.getServiceCode().matches("[a-zA-Z0-9]*")
&& validateList.getServiceGroup().chars().allMatch(Character::isDigit))
))
{
return isValid = false;
}
也在一个过滤器中尝试了所有条件
【问题讨论】:
-
在写我的答案时,我觉得你有一个错字:
if(offer.getDiscountId() != null && !offer.getProductName().isEmpty()){在第二个 sn-p 中应该是if(offer.getDiscountId() != null && !offer.getDiscountId().isEmpty()){。
标签: java list iterator java-stream