Home > Enterprise >  How to use Function interface, and use it as function argument?
How to use Function interface, and use it as function argument?

Time:03-21

I am not that good with Function interface.
How to make Function<S, Set<S>> and how to send it as paramater?\

 public class Algorithms {
    public static <S> Optional<Node<S>> search(S s0, Function<S, Set<S>> succ, Predicate<S> goal) {
        .
        .
        .
        return Optional.empty();
    }
}

CodePudding user response:

Any interface with exactly one non-default method is a functional interface, and Function meets that condition. That means you can implement it using a lambda expression. For example, let's say we're using this search function to search someone's family tree:

search(alice, (person) -> person.getChildren(), (person) -> person.getName().equals("Bob"));

The second argument, (person) -> person.getChildren(), creates a Function<Person, Set<Person>> that calls getChildren() on its argument. (We know it should accept a Person and return a Set<Person> from how we're passing it to search.) Likewise, the third argument creates a Predicate<Person> that checks if their name is "Bob".

Now, there are two "convenience" features I'm glossing over here. When the lambda only takes one argument (as is the case with both Function and Predicate), you can omit the parentheses around the name. Secondly, when a lambda only calls some method on its argument, you can use a method reference, which is just a more concise way of writing the lambda:

search(alice, Person::getChildren, person -> person.getName().equals("Bob"));

That's entirely equivalent, just more concise.

You can also implement functional interfaces the "old-school" way, i.e. by writing an (anonymous) class, but lambda syntax avoids a lot of boilerplate and is more readable. It's still fundamentally doing the same thing (and your IDE should be able to transform the one to the other, if that's helpful for you).

  •  Tags:  
  • java
  • Related