Java Stream How to - Assign your own method to a functional interface








Question

We would like to know how to assign your own method to a functional interface.

Answer

//from  w ww  . j a  va  2s .  c o m

public class Main {
  public static void main(String... args) {
    Something something = new Something();

    Converter<String, String> stringConverter = something::startsWith;
    String converted3 = stringConverter.convert("Java");
    System.out.println(converted3);    // result J
  }
}
class Something {
  String startsWith(String s) {
      return String.valueOf(s.charAt(0));
  }
}
@FunctionalInterface
interface Converter<F, T> {
    T convert(F from);
}

The code above generates the following result.