Aggregate runtime exceptions in Java 8 streams

后端 未结 4 727
北荒
北荒 2021-01-30 22:49

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         


        
4条回答
  •  借酒劲吻你
    2021-01-30 23:33

    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.

提交回复
热议问题