【发布时间】:2015-02-19 00:43:26
【问题描述】:
假设我想查看一个对象是否存在于流中,如果不存在,则抛出异常。我可以做到这一点的一种方法是使用orElseThrow 方法:
List<String> values = new ArrayList<>();
values.add("one");
//values.add("two"); // exception thrown
values.add("three");
String two = values.stream()
.filter(s -> s.equals("two"))
.findAny()
.orElseThrow(() -> new RuntimeException("not found"));
反过来呢?如果我想在找到任何匹配项时抛出异常:
String two = values.stream()
.filter(s -> s.equals("two"))
.findAny()
.ifPresentThrow(() -> new RuntimeException("not found"));
我可以只存储Optional,然后再检查isPresent:
Optional<String> two = values.stream()
.filter(s -> s.equals("two"))
.findAny();
if (two.isPresent()) {
throw new RuntimeException("not found");
}
有没有办法实现这种ifPresentThrow 的行为?尝试以这种方式投掷是一种不好的做法吗?
【问题讨论】:
-
orElseThrow的要点是在值不存在时将值转换为具有错误处理的非可选值。由于您感兴趣的是该值是否存在,为什么不使用为此目的设计的方法:isPresent?