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

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

    Just use any one of NoException (my project), jOOλ's Unchecked, throwing-lambdas, Throwable interfaces, or Faux Pas.

    // NoException
    stream.map(Exceptions.sneak().function(Class::forName));
    
    // jOOλ
    stream.map(Unchecked.function(Class::forName));
    
    // throwing-lambdas
    stream.map(Throwing.function(Class::forName).sneakyThrow());
    
    // Throwable interfaces
    stream.map(FunctionWithThrowable.aFunctionThatUnsafelyThrowsUnchecked(Class::forName));
    
    // Faux Pas
    stream.map(FauxPas.throwingFunction(Class::forName));
    

提交回复
热议问题