1

I've just started dealing with Java 8 and have some questions regarding classes design. The one relates to Optional. The main ideas are to avoid NPE / return intelligible value in case of null. Frankly I don't understand why the following is possible:

List<String> innerListA = Arrays.asList(null, "B", "C");
String result= innerListA.stream().findFirst().orElse("mock");

Last line leads to NPE in findFirst(). I understand that Optional doesn't garantee absence NPE in any possible case. But what is advantage of Optional in such simple case? If I understand correctly such a methods like findFirst() / findAny() aim to retrieve Optonal object in stream. But in its turn it doesn't garantee absense of NPE. What is the point to apply orElse() (that implies to return predictable value instead of nul) to the method that throws NPE?

I may be wrong so if anyone can explain such strange behavior please leave a comment.

aime
  • 247
  • 4
  • 16
  • 2
    There's a bit of ugliness around "Empty" values in Java. It's possible to have a value that is itself `null`, an `Optional` storing `Optional.empty()`, a `Collection`/`Stream`/`Map`/`Whatever` containing no elements, and a `Collection` that contains elements which are themselves `null`. What you're seeing is the result of an unpleasant compromise. I would say that, in general, it's a bad idea to include `null` values in a list. As long as you don't do that, the system makes sense. – Edward Peters Aug 15 '16 at 19:49
  • 3
    This is essentially equivalent to `Optional.of(null)`, which also NPEs. We had three choices with respect to "what about nulls" for streams: forbid them, embrace them, or tell the user "you can use them, but expect some collateral damage." The first seemed excessively restrictive (after all, some stream methods work perfectly fine with nulls.) The second would have greatly increased the complexity of the Stream API, for what seemed like little benefit. So we settled on the final one -- use nulls in streams at your own risk. – Brian Goetz Aug 15 '16 at 19:58
  • 1
    Also note that the spec for `findFirst()` and `findAny()` explicitly call out the case where the selected element is `null`. – Brian Goetz Aug 15 '16 at 20:15
  • I see. If I understand correctly these methods are declared to throw NPE because the ways an Optional is constructed. But why Optional(T value) constructor must check if passed value is not null? Why not to allow to instantiate Optional with null as constructor parameter if it is allowed in case of default constructor? It would let to avoid NPE in such a methods like `findFirst()` / `findAny()` – aime Aug 15 '16 at 20:30
  • I think the main advantage of `Optional.orElse` is to let you handle `null` value in **lambda expression**. – walsh Aug 16 '16 at 01:21

0 Answers0