0

Using Java Optional:

List<String> myList = .... Optional.ofNullable(myList) .ifPresentOrElse(.. do something.., ()-> log.error("missing list")); 

I do want to catch in logs when the list is null or empty. The above works perfectly for null. How can it be extended to catch the empty collections?

2
  • 2
    Where are you using the stream in this example? Commented Apr 28, 2020 at 5:25
  • 1
    so you seriously think those streams are more readable than myList == null || myList.isEmpty()? Commented Apr 28, 2020 at 5:44

2 Answers 2

4

if you really want to complicate things using Optional -

Optional.ofNullable(myList).filter(l -> !l.isEmpty()) .ifPresentOrElse(.. do something.., ()-> log.error("missing list")); 

better would be using the if-else -

if(myList !=null && !myList.isEmpty()) { // do something } else { log.error("missing list"); } 

further improvement - ensure that the List is not assigned a null value.

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

4 Comments

if the myList is null 'filter(l -> !l.isEmpty())' will through null point exception
@janith1024 no it wouldn't, ofNullable would result in an empty Optional for such cases.
yes that true I have check the implementation of ofNullable. thanks for educate me
@janith1024 that’s the very purpose of Optional. It would render Optional completely useless if you still needed to perform null-checks in the chained operations.
2

I think going with if()else{} is more readable. You can do like this:

Optional.ofNullable(myList == null || myList.isEmpty() ? null: myList) .ifPresentOrElse(.. do something.., ()-> log.error("missing list")); 

3 Comments

I thought filter was a poor solution, its still better than this! :P
@Naman filter does not cover OP requirement. OP wants to if mylist is empty log something.
thanks for the edit, and it does..if myList is empty it would result in an empty Optional and log something in the ifPresentorElse part.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.