自定义函数式接口
/**
* Function:功能描述
* * @author 一毛钱的魅力
* created on 2021/11/14
**/
public class Demo1 {
int outField=1;
public static void main(String[] args) {
new Demo1().test(1, 2, (a,b)->a+b);
}
void test(int a,int b,ISumable iSumable){
System.out.println(iSumable.sum(a,b));
}
@FunctionalInterface
interface ISumable{
public abstract int sum(int a,int b);
}
}
方法引用
含义:双冒号::为引用运算符,而它所在的表达式被称为方法引用。如果Lambda要表达的函数方案已经存在于某个方法的实现中,那么则可以通过双冒号来引用该方法作为lambda的替代者。
如果使用lambda,那么根据可推导就可以省略的原则,无需指定参数的类型,也无需指定重载的形式,它们都将自动推导。而如果使用方法引用,也是同样可以根据上下文进行推导。
函数式接口是lambda的基础,而方法引用是lambda的孪生兄弟。就是只要可以使用lambda的地方就可以使用方法引用,没有使用lambda的地方就不可以使用方法引用。
- 方法应用的自动重载
/**
* Function:功能描述
*
* @author 一毛钱的魅力
* created on 2021/11/14
**/
public class Demo2 {
static void test(Object obj,IPrinter iPrinter){
iPrinter.print(obj);
}
@FunctionalInterface
interface IPrinter{
public abstract void print(Object obj);
}
public static void main(String[] args) {
test(11,System.out::println);
}
}
- 通过实例对象引用成员方法
/**
* Function:功能描述
*
* @author 一毛钱的魅力
* created on 2021/11/14
**/
public class Demo3 {
static class Person{
int b=22;
Person(){
System.out.println(111111);
}
Person work(int a){
System.out.println(a);
System.out.println(b);
return this;
}
}
@FunctionalInterface
interface IWorker{
Object work(int a);
}
static void test(int a,IWorker iWorker){
Object work = iWorker.work(a);
}
public static void main(String[] args) {
test(11,new Person()::work);
}
}
- 通过类名称引用静态方法
/**
* Function:功能描述
*
* @author 一毛钱的魅力
* created on 2021/11/14
**/
public class Demo4 {
static class Person{
static void work(Object obj){
System.out.println(obj);
}
Person(){
System.out.println(221);
}
}
@FunctionalInterface
interface IPrinter{
void print(String str);
}
static void test(String a,IPrinter iPrinter){
iPrinter.print(a);
}
public static void main(String[] args) {
test("11",Person::work);
}
}
- super、this方式引用
/**
* Function:功能描述
*
* @author 一毛钱的魅力
* created on 2021/11/14
**/
public class Demo5 {
static class Person{
String name="zhangsan";
void teach(){
System.out.println(name+"====Person执行teach=====");
}
Person(){
System.out.println("父类构造函数");
}
}
static class Teacher extends Person{
String name="李四";
Teacher(){
System.out.println("teacher构造函数");
}
void teach(){
System.out.println(name+"----teacher执行teach------");
say(super::teach);
System.out.println("########################");
say(this::hello);
}
void say(IWorker iWorker){
iWorker.work();
}
void hello(){
System.out.println("hello");
}
}
@FunctionalInterface
interface IWorker{
void work();
}
public static void main(String[] args) {
new Teacher().teach();
}
}
- 类的构造函数引用
/**
* Function:功能描述
*
* @author 一毛钱的魅力
* created on 2021/11/14
**/
public class Demo6 {
@FunctionalInterface
interface PersonBuilder{
Person buildPerson(String name);
}
static class Person{
String name;
Person(String name){
this.name=name;
}
}
static void test(String name,PersonBuilder personBuilder){
personBuilder.buildPerson(name);
}
public static void main(String[] args) {
test("张三",Person::new);
}
}