簡體   English   中英

如何使用 java 流檢查內部列表是否不為空且變量不是 null

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM