0

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()))
4
  • 3
    Store stream.filter(predicate).collect(toList()), then check the result for emptiness. You can't store the matching strings from anyMatch like you want. Commented Dec 3, 2017 at 19:09
  • 3
    What you mean by 'handle' to the list of strings ? You want the variable names which has null value?? Commented Dec 4, 2017 at 6:23
  • what about storing the strings that are not null and from that you can find out the strings that are not contained in that list Commented Dec 4, 2017 at 12:58
  • I agree with @ChotaBheem. Can you confirm that you want to know the strings that are not null? Why, what are you going to do with a list of nulls? Have you tried Collectors.partitioningBy(field -> field == null || field.trim().isEmpty())? Commented Dec 4, 2017 at 16:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can also use more methods from Stream API like anyMatch, noneMatch like Sajna did in the question, and combine that with the method reference that you show in your filter() call

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.