How can I throw CHECKED exceptions from inside Java 8 streams?

前端 未结 18 2001
你的背包
你的背包 2020-11-22 06:59

How can I throw CHECKED exceptions from inside Java 8 streams/lambdas?

In other words, I want to make code like this compile:

public List

        
18条回答
  •  星月不相逢
    2020-11-22 07:43

    You can also write a wrapper method to wrap unchecked exceptions, and even enhance wrapper with additional parameter representing another functional interface (with the same return type R). In this case you can pass a function that would be executed and returned in case of exceptions. See example below:

    private void run() {
        List list = Stream.of(1, 2, 3, 4).map(wrapper(i ->
                String.valueOf(++i / 0), i -> String.valueOf(++i))).collect(Collectors.toList());
        System.out.println(list.toString());
    }
    
    private  Function wrapper(ThrowingFunction function, 
    Function onException) {
        return i -> {
            try {
                return function.apply(i);
            } catch (ArithmeticException e) {
                System.out.println("Exception: " + i);
                return onException.apply(i);
            } catch (Exception e) {
                System.out.println("Other: " + i);
                return onException.apply(i);
            }
        };
    }
    
    @FunctionalInterface
    interface ThrowingFunction {
        R apply(T t) throws E;
    }
    

提交回复
热议问题