2015-06-06 10 views
26

Ho il seguente Stream:Evitare NoSuchElementException con Stream

Stream<T> stream = stream(); 

T result = stream.filter(t -> { 
    double x = getX(t); 
    double y = getY(t); 
    return (x == tx && y == ty); 
}).findFirst().get(); 

return result; 

Tuttavia, non v'è sempre un risultato che mi dà il seguente errore:

NoSuchElementException: No value present

Così come posso restituire un null se non c'è valore presente?

risposta

49

Si può usare Optional.orElse, è molto più semplice di controllo isPresent:

T result = stream.filter(t -> { 
    double x = getX(t); 
    double y = getY(t); 
    return (x == tx && y == ty); 
}).findFirst().orElse(null); 

return result; 
17

Stream#findFirst() restituisce un Optional che esiste in modo specifico in modo che non sia necessario operare sui valori null.

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

In caso contrario, Optional#get() getta un NoSuchElementException.

If a value is present in this Optional , returns the value, otherwise throws NoSuchElementException .

Un Optional esporrò mai il suo valore se è null.

Se proprio dovete, basta controllare isPresent() e tornare null te stesso.

Stream<T> stream = stream(); 

Optional<T> result = stream.filter(t -> { 
    double x = getX(t); 
    double y = getY(t); 
    return (x == tx && y == ty); 
}).findFirst(); 

if (result.isPresent()) 
    return result.get(); 
return null; 
+0

Oppure basta andare con la restituzione di un 'Optional', che potrebbe avere alcuni vantaggi rispetto alla restituzione di null. – Zhedar

1

Un metodo alternativo per la sostituzione del Optional.get (che più probabile che non fallisce intenzioni dell'utente con un NoSuchElementException) è con un API più verbose introdotta in JDK10 definita come Optional.orElseThrow(). In author's words -

Optional.get() is an "attractive nuisance" and is too tempting for programmers, leading to frequent errors. People don't expect a getter to throw an exception. A replacement API for Optional.get() with equivalent semantics should be added.

Note: - L'implementazione sottostante di entrambe queste API è lo stesso, ma quest'ultimo legge più chiaramente che NoSuchElementException sarebbe stato gettato per difetto se il valore non è presente che inlines all'attuale implementazione Optional.orElseThrow​(Supplier<? extends X> exceptionSupplier) utilizzata dai consumatori come alternativa esplicita.

+0

Più precisamente per rispondere ['Optional.get()' senza 'isPresent()' check] (https://stackoverflow.com/questions/38725445/optional-get-without-ispresent-check) contrassegnato come duplicato di questo thread . – nullpointer