Novice User
Novice User

Reputation: 3834

Java 8 Optional detect empty collection

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?

Upvotes: 0

Views: 3048

Answers (2)

Naman
Naman

Reputation: 32036

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.

Upvotes: 4

Hadi
Hadi

Reputation: 17299

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"));

Upvotes: 2

Related Questions