Java 使用 Stream 避免 NoSuchElementException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30686215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:59:53  来源:igfitidea点击:

Avoid NoSuchElementException with Stream

javajava-8java-streamoptional

提问by clankill3r

I have the following Stream:

我有以下几点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;

However, there is not always a result which gives me the following error:

但是,并不总是有结果给我以下错误:

NoSuchElementException: No value present

NoSuchElementException:不存在值

So how can I return a nullif there is no value present?

那么null如果没有值,我该如何返回 a呢?

采纳答案by Tagir Valeev

You can use Optional.orElse, it's much simpler than checking isPresent:

您可以使用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;

回答by Sotirios Delimanolis

Stream#findFirst()returns an Optionalwhich exists specifically so that you don't need to operate on nullvalues.

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 trueand get()will return the value.

可能包含也可能不包含非空值的容器对象。如果值存在,isPresent()将返回trueget()返回值。

Otherwise, Optional#get()throws a NoSuchElementException.

否则,Optional#get()抛出一个NoSuchElementException.

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

如果 this 中存在一个值Optional,则返回该值,否则抛出NoSuchElementException

An Optionalwill never expose its value if it is null.

Optional如果是 ,An将永远不会公开其值null

If you really have to, just check isPresent()and return nullyourself.

如果您真的必须这样做,请自行检查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;

回答by Naman

An alternate method for replacing the Optional.get(which more likely than not fails the user's intentions with a NoSuchElementException) is with a more verbose API introduced in JDK10 termed as Optional.orElseThrow(). In author's words-

替换 的另一种方法Optional.get(使用 NoSuchElementException 很可能使用户的意图失败)是使用 JDK10 中引入的更详细的 API,称为Optional.orElseThrow(). 用作者的话来说——

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.

Optional.get()是一个“有吸引力的麻烦”,对程序员来说太诱人了,导致经常出错。人们不希望 getter 抛出异常。Optional.get()应添加具有等效语义的替代 API 。

Note:- The underlying implementation of both these APIs is same, yet the latter reads out more clearly that a NoSuchElementException would be thrown by default if the value is not present which inlines to the existing Optional.orElseThrow?(Supplier<? extends X> exceptionSupplier)implementation used by consumers as an explicit alternate.

注意:- 这两个 API 的底层实现是相同的,但后者更清楚地指出,如果不存在值,则默认情况下将抛出 NoSuchElementException,该值内联到Optional.orElseThrow?(Supplier<? extends X> exceptionSupplier)消费者用作显式替代的现有实现。