简体   繁体   中英

Using Java Stream anymatch with filter for null check

I am using Stream.anymatch to check if any of the four string is empty or null- Can we get handle to the list of Strings that are null as a part of this check for subsequent logic

if(Stream.of(stringA, stringB,stringC, stringD)
        .anyMatch(field -> field == null || field.trim().isEmpty()))

I would suggest you use StringUtils.isBlank() from Apache Commons libraries https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html

Then you can use a temporary value to store Objects with blank values using

List<String> blank = Stream.of(stringA, stringB,stringC, stringD)
                           .filter(StringUtils::isBlank)
                           .collect(Collectors.toList());
if (blank.size() > 0) {
      // your code here
}

I suggest you use multiple if(StringUtils.isBlank(stringX)){} statements if you need to execute different code in each case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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