1

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).

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Sachi97
  • 39
  • 8
  • main idea of this code is to iterate over list while also handling case when given list is null. when given list is null - using empty list will just result in no further operations and not null pointer exception – Daniel Feb 03 '23 at 17:07
  • List can not be 'literal null' try yourself If you r fetching any records from repository here is the example (Select * entity where abc = ?1) List getAllMatchedRecords(param1); – Sachi97 Feb 03 '23 at 17:57
  • 1
    It’s not clear what your question is aiming at. If the list can never be `null`, a code construct that can handle both cases, `null` and non-`null`, will obviously handle that case. If `list` can never be `null`, using an optional is obsolete, and generally, developers should not use `null` for `List` and hence, not have a need for optional lists, however, there is no reason why this shouldn’t work. – Holger Feb 10 '23 at 14:42

1 Answers1

5

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.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • 2
    Good answer (+1). I might, just might prefer `Optional.ofNullable(list).map(List::stream).orElse(Stream.empty())`, but its a matter of taste and inclination. – Ole V.V. Feb 08 '23 at 19:25