引用类方法
@FunctionalInterface
interface Fn
{
double cal(double d1,double d2);
}
public class InvokeStaticMethod
{
public static void main(String[] args)
{
// 引用类方法
Fn fn1 = (d1, d2) -> Math.hypot(d1, d2);
System.out.println(fn1.cal(3, 4));
// 本质一样
Fn fn2 = Math::hypot;
fn2.cal(3, 4);
}
}
引用实例方法
@FunctionalInterface
interface Converter
{
int convert(String str);
}
public class InvokeInstanceMethod
{
public static void main(String[] args)
{
Converter c1 = str -> str == null ? 0 : str.length();
System.out.println(c1.convert("InvokeInstanceMethod by lambda"));
Converter c2 = String::length;
System.out.println(c2.convert("invoke by ::"));
}
}
带多个参数的实例方法
@FunctionalInterface
interface Converter
{
String convert(String str,int start,int end);
}
public class InvokeInstanceMethod1
{
public static void main(String[] args)
{
Converter c1 = (str,start,end) -> str.substring(start,end);
System.out.println(c1.convert("InvokeInstanceMethod by lambda",2,4));
Converter c2 = String::substring;// 参数1的类型::某个方法
System.out.println(c2.convert("invoke by ::",2,4));
}
}
引用特定对象的实例方法
@FunctionalInterface
interface Convert
{
String convert(int start, int end);
}
public class InvokeConcreteObjInstanceMethod
{
public static void main(String[] args)
{
Convert c1 = (start,end) -> "Hello World!".substring(start,end);
System.out.println(c1.convert(2, 6));
Convert c2 = "Hello World!"::substring;
System.out.println(c2.convert(2, 8));
}
}
构造器引用
import java.util.Date;
@FunctionalInterface
interface Test
{
Date cal(int a, int b, int c);
}
public class InvokeConstructorByLambda
{
public static void main(String[] args)
{
Test t1 = (a, b, c) -> new Date(a, b, c);
System.out.println(t1.cal(119,7,17));
Test t2 = Date::new;
System.out.println(t2.cal(119,7,17));
}
}