[英]How to check if the inner list is not empty and the variable is not null using java streams
如何将此循环组合到单个 stream 中?
final boolean hasEmptyFooDesc = data.getFoo().stream().anyMatch(fooDTO -> CollectionUtils.isEmpty(fooDTO.getFooDesc()));
final boolean hasDescriptions = data.getFoo().stream().flatMap(fooDTO -> fooDTO.getFooDesc().stream()).allMatch(fooDescDTO -> fooDescDTO.getDescription() != null);
if (hasEmptyFooDesc || !hasDescriptions) {
throw new BadRequestException();
}
编写一个方法,例如isBad
:
static boolean isBad(DtoType fooDto) {
return CollectionUtils.isEmpty(fooDTO.getFooDesc())
|| fooDTO.getFooDesc().stream().anyMatch(fooDescDTO -> fooDescDTO.getDescription() == null);
}
然后调用:
if (data.getFoo().stream().anyMatch(YourClass::isBad)) {
throw ...
}
(Ofc,您实际上并不需要这里的方法,您可以将其写为 lambda。但使用方法可能更容易阅读)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.