-6

Java 8 Optional method get throws an exception when does not exists the element. Why does throws exception instead of return null or an Optional empty?

  • 1
    What is an _empty value_? – Sotirios Delimanolis Jun 11 '15 at 15:18
  • 6
    That's the whole point of Optional: to force you to handle the case when there is no value appropriately. Strongly related: http://stackoverflow.com/questions/23454952/uses-for-java8-optional – assylias Jun 11 '15 at 15:19
  • "static Optional empty() Returns an empty Optional instance." Thanks, @assylias – Homilzio Trovoada Santos Jun 11 '15 at 15:23
  • So you want an empty `Optional` to return another empty `Optional`? – Sotirios Delimanolis Jun 11 '15 at 15:28
  • 4
    This is the _entire point_, that it doesn't return `null`. – Louis Wasserman Jun 11 '15 at 15:34
  • I am not sure the downvoting is entirely justified here. Maybe the phrasing of the question is not quite adequate, especially in the alternative options proposed for the Optional.get, but I can see why the OP is confused with regards to the method throwing an Exception. In fact Brian Goetz himself [acknowledges](http://stackoverflow.com/questions/26327957/should-java-8-getters-return-optional-type/26328555#26328555) that this was not a totally fortunate decision – djsecilla May 24 '16 at 09:31

2 Answers2

2

Use .orElse(null) if you want null. The idea of Optional is to force you to explicitly handle the absence of the value.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
0

You can you Optional.orElse(null) if you need null or the value

Optional optional  = Optional.empty();
System.out.println(optional.orElse(null));

If there is some operation or action you want to perform you an use OptionalifPresent(Consumer operationToPerform)

optional.ifPresent(o->{ // operation to perform
System.out.println(o); });
Manasi
  • 765
  • 6
  • 17