Sachi97
Sachi97

Reputation: 41

Optional.ofNullable() on List

I need an assistance on one of the optional concepts of java 8+. I have been seeing developers using Optional.ofNullable on list object which is incorrect and I am not sure how its been working perfectly without bugs/defect. Code goes this way

Note: list object is being captured by making DB call from repository layer.

Optional.ofNullable(list) .orElse(Collections.emptyList()) .stream().forEach(x-> { ------ ------};);

List cannot be literal null if there is no elements it would be empty([]) so, how can it handle Optional.ofNullable() correctly? I tried dummy code to test by adding print statement in forEach It would print in both cases(list empty as well not empty).

Upvotes: 1

Views: 7862

Answers (2)

Emanuel Trandafir
Emanuel Trandafir

Reputation: 1653

If you really want to use Optional here, you can do something simpler, like this:

Optional.ofNullable(list).ifPresnt(l -> l.forEach(....))

But, in my opinion, a simple null-check should do:

if(list != null) {
    list.forEach(x -> {...})
}

Upvotes: 0

WJS
WJS

Reputation: 40044

If the list is null, which it could be depending on use case, it creates an empty list and prints its contents which will be empty (but no exception will be thrown). If it is not empty, it will print its contents.

List<String> list = null;
 // prints empty list
 Optional.ofNullable(list).orElse(Collections.emptyList()).stream()
         .forEach(System.out::println);
 list = List.of("A", "B", "C");
 // print the contents.
 Optional.ofNullable(list).orElse(Collections.emptyList()).stream()
         .forEach(System.out::println);

Prints

A
B
C

I presume the idea is to handle a null list by processing an empty Collection.

Upvotes: 5

Related Questions