Purpose of Functional Interfaces in Java8

前端 未结 3 1031
粉色の甜心
粉色の甜心 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 02:03

    Although you ask "Is that it?", it's very nice that we don't have to write a new interface ever time we want type for a lambda.

    Ask yourself, if you're reading an API, which is easier for a programmer to use:

    public void processUsers(UserProcessor userProcessor);
    

    ... or ...

    public void processUsers(Consumer userProcessor);
    

    With the former, I have to go and take a look at UserProcessor to find out what one is, and how I could create one; I don't even know it could be implemented as a lambda until I go and find out. With the latter, I know immediately that I can type u -> System.out.println(u) and I'll be processing users by writing them to stdout.

    Also the author of the library didn't need to bloat their library with Yet Another Type.

    In addition, if I coerce a lambda to a Functional Type, I can use that type's composition methods, for example:

     candidates.filter( personPredicates.IS_GRADUATE.negate());
    

    That gives you Predicate methods and(), or(), negate(); Function methods compose(), andThen() -- which your custom type would not have unless you implemented them.

提交回复
热议问题