假设我想查看流中是否存在对象,如果它不存在,则抛出异常.我可以做的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"));
Run Code Online (Sandbox Code Playgroud)
反过来呢?如果我想在发现任何匹配时抛出异常:
String two = values.stream()
.filter(s -> s.equals("two"))
.findAny()
.ifPresentThrow(() -> new RuntimeException("not found"));
Run Code Online (Sandbox Code Playgroud)
我可以存储Optional,并在isPresent之后进行检查:
Optional<String> two = values.stream()
.filter(s -> s.equals("two"))
.findAny();
if (two.isPresent()) {
throw new RuntimeException("not found");
}
Run Code Online (Sandbox Code Playgroud)
有没有办法实现这种ifPresentThrow行为?试图以这种方式投掷一个不好的做法?
ber*_*rdt 47
ifPresent()如果您的过滤器找到任何内容,您可以使用该调用抛出异常:
values.stream()
.filter("two"::equals)
.findAny()
.ifPresent(s -> {
throw new RuntimeException("found");
});
Run Code Online (Sandbox Code Playgroud)
Stu*_*rks 25
既然您只关心是否找到匹配项,而不是实际找到的匹配项,那么您可以使用anyMatch它,而您根本不需要使用它Optional:
if (values.stream().anyMatch(s -> s.equals("two"))) {
throw new RuntimeException("two was found");
}
Run Code Online (Sandbox Code Playgroud)
userOptional.ifPresent(user1 -> {throw new AlreadyExistsException("Email already exist");});
Run Code Online (Sandbox Code Playgroud)
这里中括号是强制性的,否则它会显示编译时异常
{throw new AlreadyExistsException("Email already exist");}
public class AlreadyExistsException extends RuntimeException
Run Code Online (Sandbox Code Playgroud)
并且异常类必须扩展运行时异常