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

前端 未结 18 1973
你的背包
你的背包 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:20

    You cannot.

    However, you may want to have a look at one of my projects which allows you to more easily manipulate such "throwing lambdas".

    In your case, you would be able to do that:

    import static com.github.fge.lambdas.functions.Functions.wrap;
    
    final ThrowingFunction> f = wrap(Class::forName);
    
    List classes =
        Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
              .map(f.orThrow(MyException.class))
              .collect(Collectors.toList());
    

    and catch MyException.

    That is one example. Another example is that you could .orReturn() some default value.

    Note that this is STILL a work in progress, more is to come. Better names, more features etc.

提交回复
热议问题