Functions are similar to predicates except that they can return any type of result. Not just boolean.
It has only one method called apply and it can take any types of parameters and return any type.
interface Function(T, R) {//T is the parameter, R is the return value
R apply(T t);
}
Handson
public class FunctionTest {
public static void main(String[] args) {
Function<String, Integer> f = s -> s.length();
System.out.println(f.apply("john"));//4
}
}
:: Operator / method reference
double colon operator: map methods and constructors to a functional interface method
You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.
(map to myinterface class)method could be static or non-static
the only rule is that parameter type should be the same, others could be different
method reference handson example
public class MethodReference {
public static void myMethod() {
for (int i = 0; i <= 10; i++) {
System.out.println("child thread");
}
}
public static void main(String[] args) {
Runnable r = MethodReference::myMethod;
Thread t = new Thread(r);
t.start();
for (int i = 0; i <= 10; i++) {
System.out.println("parent thread");
}
}
}
reference a constructor
public class MyClass {
private String s;
MyClass(String s) {
this.s = s;
System.out.println("inside the constructor");
}
}
public interface MyInterface {
MyClass get(String s);
}
public class Test {
public static void main(String[] args) {
MyInterface f1 = s -> new MyClass(s);
f1.get("using lambda");
//inside the constructor using lambda
MyInterface f2 = MyClass::new;//map constructor to get method
f2.get("using constructor mapping");
//inside the constructor using constructor mapping
}
}