0
点赞
收藏
分享

微信扫一扫

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 函数式接口​​


举报

相关推荐

c语言--指针作为函数参数传递

0 条评论