your code is working perfectly, apart from a missing semi colon at the end of the throw new ...
line, and from a missing a return statement that may be hidden in // code here
.
What you can't do is throw a checked exception (which RuntimeException is not) because checked exception are part of the method signature and the Predicate.test method do not declare one.
EDIT :
To see more precisely what is happening and why you can't throw a checked exception here, here is how you could have written the code without lambda :
From this :
public Person myMethod() throws IOException {
Person result = persons.stream()
.filter(x -> {
if ("test".equals(x.getName() ) ) {
throw new IOException("not possible inside stream y ?"); //any checked exception
}
//code here
return true;
});
return person;
}
to this :
public Person myMethod() throws IOException {
Person result = persons.stream()
.filter(new Predicate<Person>() {
public boolean test(Person x) {
if ("test".equals(x.getName() ) ) {
throw new IOException("not possible inside stream y ?"); //any checked exception
}
//code here
return true;
}
});
return person;
}
As you can see, the code inside the lambda expression is now inside the test
method of an anonymous Predicate
class, which is not declaring any checked exception.
Why Predicate
? Because it is what the filter
method is expecting, and you can use a lambda instead of a conventional object because it is a single method interface : only test
is abstract, and your lambda signature should be the same as the Predicate.test
method.
If you really wish to be able to handle checked exceptions, the linked post (in a comment from Frederico) show some ways to bypass these limitations.