Java---新特性_函数式接口详解

函数式接口

Lambda表达式使用的前提,就是接口必须是一个函数式接口。

定义

如果在接口中,只有一个抽象方法,那么这个接口就是函数式接口

格式

使用注解来检查当前接口是否是一个函数式接口@FunctionalInterface,如果不是函数式接口,则编译会报错。

//表明当前接口有且只有一个抽象方法,如果有多个方法则会报错
@FunctionalInterface
public interface MyIn1 {
    public void method1();
}
作用

主要用于函数式编程(即使用lambda表达式编程)

消费型接口(Consumer)

1.抽象方法
T accept();

2.系统接口实现:
在这里插入图片描述
代码示例:

public class ConsumerInterfaceTest {
    public static void main(String[] args) {
        //消费型接口有参数无返回值

        Consumer<String> con=(x)->System.out.println(x);
        test1(500,"吃饭",con);
    }

    //提供一个方法
    //最终打印:花了多少钱,干了什么事
    public static void test1(int money, String str, Consumer<String> con){
        System.out.println("花了"+money+"钱");
        con.accept(str);
    }
}
方法引用

在写一个函数式接口时,方法的实现已经被某个其他的对象实现了,就不需要在lambda中再次调用这个实现,而可以直接使用那个已经定义好的方法

1.格式
函数式接口 名称=对象名::方法名称
函数式接口 名称=类名::静态方法名称

2.作用
把已经实现的接口作为一个引用,赋值给某个函数式接口的引用,可以把这个引用当做方法的返回值,也可以作为方法的实际参数进行传递。

public static void main(String[] args) {
		//1.引用JDK存在的方法
		Consumer<String> con = (x)-> System.out.println("zhangsan");
		con.accept("zhangsan");
		//下面代码引用了System.out对象的println方法
		Consumer<String> con1 = System.out::println;
		con1.accept("zhangsan");

		//2.引用其他自定义类已经存在的普通方法
		MyClass m = new MyClass();
		Consumer<Integer> con2 = m::test1;
		con2.accept(7);

		//3.引用其他类中已经存在的静态方法
		Consumer<Integer> con3 = MyClass::test3;
		con3.accept(6);
	}

class MyClass{
	public void test1(int x){
		x = x+1;
		x++;
		x = x-7;
		System.out.println(x);
	}
	public static void test3(int x){
		x = x*3;
		x++;
		System.out.println(x);
	}
}
供给型接口(Supplier)

系统中接口的实现:
在这里插入图片描述
代码示例:

public class SupplierInterfaceTest {
    public static void main(String[] args) {
        //供给型接口无参数有返回值
        Supplier<Integer> p = ()->{
            Random r=new Random();
            int x=r.nextInt(10)+1;
            return x;
                };

        ArrayList<Integer> arr = getArr(10, p);
        System.out.println(arr);

    }

    //定义一个方法,返回一个集合,集合中n个满足条件的数据
    //要求数据是随机数字,在1-10之间
    public static ArrayList<Integer> getArr(int n, Supplier<Integer> s){
        ArrayList<Integer> arr = new ArrayList<>();
        for(int i=1;i<=n;i++){
            Integer x=s.get();
            arr.add(x);
        }
        return arr;
    }
}
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值