我有以下 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;
但是,并不总是有结果给我以下错误:
NoSuchElementException: No value present
那么如果没有值,我该如何返回 null
?
最佳答案
您可以使用 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;
关于java - 使用 Stream 避免 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30686215/