Java:函数式接口(Functional Interface)实现将函数作为方法参数传递

1、函数式接口简介

函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。

使用场景:将函数作为方法参数传递

2、函数式接口案例

1、定义函数式接口

package com.example;


// @FunctionalInterface注解 检查一个接口是否是一个函数式接口
@FunctionalInterface
public interface MyFunctionInterface {
    void show();
}

2、使用函数式接口

package com.example;


public class Demo {
    // 定义一个方法以函数式接口作参数
    public static void test(MyFunctionInterface myFunctionInterface) {
        myFunctionInterface.show();
    }

    public static void main(String[] args) {
        // 1.使用匿名内部类的方式
        MyFunctionInterface myFunctionInterface = new MyFunctionInterface() {
            @Override
            public void show() {
                System.out.println("Hello 1");
            }
        };

        test(myFunctionInterface);

        // 2.直接传递匿名内部类
        test(new MyFunctionInterface() {
            @Override
            public void show() {
                System.out.println("Hello 2");
            }
        });

        // 3.使用Lambda表达式的方式使用函数式接口
        test(() -> System.out.println("hello 3"));
    }
}

3、常用函数式接口

1、消费型接口

定义

// 有参无返回值
@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

示例

package com.example;


import java.util.function.Consumer;

public class Demo {
    // 定义一个方法以函数式接口作参数
    public static void test(Consumer<Integer> consumer, Integer value) {
        consumer.accept(value);
    }

    public static void main(String[] args) {
        test((value) -> System.out.println(value), 20);
        // 20
    }
}

2、供给型接口

定义

// 无参有返回值
@FunctionalInterface
public interface Supplier<T> {
    T get();
}

示例

package com.example;


import java.util.function.Supplier;

public class Demo {

    public static Integer test(Supplier<Integer> supplier) {
        return supplier.get();
    }

    public static void main(String[] args) {
        Integer value = test(() -> 20);
        System.out.println(value);
        // 20
    }
}

3、函数型接口

定义

// 有参有返回值
@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}

示例

package com.example;


import java.util.function.Function;

public class Demo {

    public static Integer test(Function<Integer, Integer> function, Integer value) {
        return function.apply(value);
    }

    public static void main(String[] args) {
        Integer value = test((x) -> x * 10, 2);
        System.out.println(value);
        // 20
    }
}


参考
java核心技术,函数式编程接口详解
Java 8 函数式接口

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值