Optional.get () vs overloaded Optional.orElseThrow () in Java-10

How can you avoid explicit generation Exceptionwhen trying to get a value from Optionalor when using ? Optional.get

This is currently possible orElseThrowAPI or orElseThrowas:

// exception could be replaced with any other
Integer opt = anyOddInStream.orElseThrow(
                           () -> new NoSuchElementException("No value present"));

and yet, the immediate implementation is getdisappointing (when someone might not want to explicitly throw an exception) when trying to access something like

// the following not only just fails but throws an exception as well
Integer previous = anyOddInStream.get();

What if someone wants to make sure that Optionaleither matters, and if not, they don’t want to continue to spread nullforward?

+9
source share
3 answers

Java 8 , , , - Optional.get(), isPresent(), Optional . ( , , .)

Java 9 Optional.get(), ... . orElseThrow() 10 (. https://bugs.openjdk.java.net/browse/JDK-8140281) get(). IDE get(), orElseThrow(), . - " " ; get() .

, , , , .

+23

, Optional.get() - . Optional.isPresent() Optional.get(). :

http://royvanrijn.com/blog/2016/04/deprecating-optional-get/

Optional.get(). null , Optional.orElse(null).

+5

Optional.get (, , ), , API, JDK10, Optional.orElseThrow(). -

Optional.get() - " " , . , . API Optional.get() .

Optional<Integer> anyOddInStream = Stream.of(2, 4, 6, 8)
                                         .filter(x -> x % 2 == 1)
                                         .findAny();
// one could be well aware of the possible exception handling while reading this 
var current = anyOddInStream.orElseThrow(); 

Note : - The base implementation of these two API is the same, but the latter reads that by more clearly will be thrown out , if the value is absent, indicating that the existing Extends the implementation used by consumers as a clear alternative. NoSuchElementExceptionNoSuchElementException Optional.orElseThrow(Supplier<? extends X> exceptionSupplier) Optional.orElseThrow(Supplier<? extends X> exceptionSupplier)

+4
source

Source: https://habr.com/ru/post/1694611/


All Articles