Let\'s say I have a method which throws a runtime exception. I\'m using a Stream
to call this method on items in a list.
class ABC {
public voi
Here's a variation on the theme of mapping-to-exceptions.
Start with your existing doStuff
method. Note that this conforms to the functional interface Consumer
.
public void doStuff(MyObject myObj) {
if (...) {
throw new IllegalStateException("Fire! Fear! Foes! Awake!");
}
// do stuff...
}
Now write a higher-order function that wraps this and turns this into a function that might or might not return an exception. We want to call this from flatMap
, so the way "might or might not" is expressed is by returning a stream containing the exception or an empty stream. I'll use RuntimeException
as the exception type here, but of course it could be anything. (In fact it might be useful to use this technique with checked exceptions.)
Function> ex(Consumer cons) {
return t -> {
try {
cons.accept(t);
return Stream.empty();
} catch (RuntimeException re) {
return Stream.of(re);
}
};
}
Now rewrite doStuffOnList
to use this within a stream:
void doStuffOnList(List myObjs) {
List exs =
myObjs.stream()
.flatMap(ex(this::doStuff))
.collect(Collectors.toList());
System.out.println("Exceptions: " + exs);
}