2015-06-06 70 views
26

我有以下Stream与流避免NoSuchElementException异常

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; 

但是,并不总是这给了我下面的错误结果:

NoSuchElementException: No value present

所以,我怎么可以返回null如果目前没有价值?

回答

49

您可以使用Optional.orElse,它比检查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()返回一个Optional,它专门存在以便您不需要操作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.

否则,Optional#get()抛出一个NoSuchElementException。如果是null

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

Optional永远不会暴露其价值。

如果您确实需要,只需查看isPresent()并自行返回null

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

或者直接返回'Optional',这可能比返回null有一些优点。 – Zhedar

1

更换Optional.get(其中较有可能有一个NoSuchElementException失败,用户的意图)的另一种方法是用在JDK10中引入了更为详细的API,称为Optional.orElseThrow()。在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.

: - 无论这些API的底层实现是一样的,但后者读出更加清楚地表明一个NoSuchElementException默认会被抛出,如果该值没有出现,这内联到消费者使用现有的Optional.orElseThrow​(Supplier<? extends X> exceptionSupplier)作为明确的替代方案。

+0

更准确地说,如果没有'isPresent()'检查] ['Optional.get()'](https://stackoverflow.com/questions/38725445/optional-get-without-ispresent-check)标记为此线程的重复。 – nullpointer