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
There are already some implementations of Try
monad for Java. I found better-java8-monads library, for example. Using it, you can write in the following style.
Suppose you want to map your values and track all the exceptions:
public String doStuff(String s) {
if(s.startsWith("a")) {
throw new IllegalArgumentException("Incorrect string: "+s);
}
return s.trim();
}
Let's have some input:
List input = Arrays.asList("aaa", "b", "abc ", " qqq ");
Now we can map them to successful tries and pass to your method, then collect successfully handled data and failures separately:
Map>> result = input.stream()
.map(Try::successful).map(t -> t.map(this::doStuff))
.collect(Collectors.partitioningBy(Try::isSuccess));
After that you can process successful entries:
System.out.println(result.get(true).stream()
.map(t -> t.orElse(null)).collect(Collectors.joining(",")));
And do something with all the exceptions:
result.get(false).stream().forEach(t -> t.onFailure(System.out::println));
The output is:
b,qqq
java.lang.IllegalArgumentException: Incorrect string: aaa
java.lang.IllegalArgumentException: Incorrect string: abc
I personally don't like how this library is designed, but probably it will be suitable for you.
Here's a gist with complete example.