The functional interfaces in Java don’t declare any checked or unchecked exception. We need to change the signature of the methods from:
boolean isActive() throws IOException;
String getNumber() throwsIOException;
To:
boolean isActive();
String getNumber();
Or handle it with try-catch block:
public Set<String> getActiveAccountNumbers() {
Stream<Account> s = accounts.values().stream();
s = s.filter(a ->
try{
a.isActive();
}catch(IOException e){
throw new RuntimeException(e);
}
);
Stream<String> ss = s.map(a ->
try{
a.getNumber();
}catch(IOException e){
throw new RuntimeException(e);
}
);
return ss.collect(Collectors.toSet());
}
Another option is to write a custom wrapper or use a library like ThrowingFunction. With the library we only need to add the dependency to our pom.xml:
<dependency>
<groupId>pl.touk</groupId>
<artifactId>throwing-function</artifactId>
<version>1.3</version>
</dependency>
And use the specific classes like ThrowingFunction, ThrowingConsumer, ThrowingPredicate, ThrowingRunnable, ThrowingSupplier.
At the end the code looks like this:
public Set<String> getActiveAccountNumbers() {
return accounts.values().stream()
.filter(ThrowingPredicate.unchecked(Account::isActive))
.map(ThrowingFunction.unchecked(Account::getNumber))
.collect(Collectors.toSet());
}