Purpose of Functional Interfaces in Java8

前端 未结 3 1061
粉色の甜心
粉色の甜心 2021-01-06 01:22

I\'ve come across many questions in regards of Java8 in-built Functional Interfaces, including this, this, this and this. But all ask about \"why only one m

3条回答
  •  天命终不由人
    2021-01-06 01:50

    Java API provides many built-in Function Interfaces for java developers. and we can use the built-in Function Interfaces many times. but there two reasons to use a Customer Function Interface.

    1. Use a Customer Function Interface to describe explicitly what's like.

      let's say you having a class User with a name parameter on the constructor.when you use the built-in Function Interface to refer the constructor the code like below:

      Function userFactory=User::new;
      

      if you want describe it clearly you can introduce your own Function Interface, e.g:UserFactory;

      UserFactory userFactory=User::new;
      

      another reason to use Custom Function Interface due to built-in Function Interface is confused in somewhere. when you see a parameter with type Function,is it create a new user or query an user from database or remove the user by a string and return the user,...?if you use an exactly Function Interface you know what it doing,as an UserFactory is create an user from a string username.

    2. Use a Customer Function Interface to processing checked Exception in java built-in Function Interface.

      Due to the built-in Function Interface can't be throwing a checked Exception,the problem occurs when you processing something in lambda expression that may be throws a checked exception,but you don't want to use the try/catch to handle the checked Exception,which will be tends to many code difficult to read in lambda expression.then you can define your own Function Interface that throws any CheckedException and adapt it to the built-in Function Interface when using java API.the code like as below:

      //if the bars function throws a checked Exception,you must catch the exception
      Stream.of(foos).map(t->{
         try{
            return bars.apply(t);
         }catch(ex){//handle exception}
      });
      

      you also can define your own Function Interface throws a checked Exception,then adapt it to built-in Function,let's say it is a Mapping interface,the code below:

      interface Mapping {
        R apply(T value) throws Exception;
      }
      
      private Function reportsErrorWhenMappingFailed(Mapping mapping){
        return (it)->{
          try{
            return mapping.apply(it);
          }catch(ex){
            handleException(ex);
            return null;
          }
        };
      } 
      Stream.of(foos).map(reportsErrorWhenMappingFailed(bars));
      

提交回复
热议问题