Java8的Lambda表达式

Java8的Lambda表达式

Lambda表达式与函数式接口

函数式接口是只包含一个抽象方法声明的接口。java.lang.Runnable 就是一种函数式接口,在 Runnable 接口中只声明了一个方法 void run()。我们使用匿名内部类来实例化函数式接口的对象,有了 Lambda 表达式,这一方式可以得到简化。

@FunctionalInterface 是 Java 8 新加入的一种接口,用于指明该接口类型声明是根据 Java 语言规范定义的函数式接口。

如下所示,在WorkerInterface接口上,使用FunctionalInterface声明后,在这个接口里面不写方法或者写两个方法,编译器都会报错。

@FunctionalInterface
public interface WorkerInterface{
    public void doSomeWork();
}

Lambda表达式的使用

1). Thread Runable

new Thread(()-> System.out.println(Thread.currentThread().getName())).start();

new Thread(()-> {
System.out.println(Thread.currentThread().getName());
}).start();

2). 有参数无返回值

@FunctionalInterface
public interface Interface1{
    public void work1(String str);
}

// 带类型
Interface1 interface1=(String str)->{
System.out.println("Interface1带类型的:"+str);
};

interface1.work1("传入参数");
// 不带类型
Interface1 interface11=(str)->{
System.out.println("Interface1不带类型的:"+str);
};

interface11.work1("传入参数");


// 不带括号
Interface1 interface12=str->
System.out.println("Interface1不带括号的:"+str);

interface12.work1("传入参数");


// 不带大括号
Interface1 interface13=str->{
System.out.println("Interface1不带大括号:"+str);
};

interface13.work1("传入参数");

3). 有参数有返回值

Interface2 interface21=clz->"直接返回:"+clz.getName();
System.out.println(interface21.work2(String.class));

Interface2 interface22=clz->{
return "return返回:"+clz.getName();
};

System.out.println(interface22.work2(Integer.class));

java8的双冒号表达式,Iterable接口的forEach遍历,Consumer接口(函数式接口)

 List<String> list = Arrays.asList("aaa","bbb","ccc");
 System.out.println("通常的遍历方式");
 // 1.通常的遍历方式
 for(String str: list) {
 System.out.println(str);
 }
 System.out.println("使用Lambda表达式遍历");
 // 2.使用Lambda表达式遍历
 list.forEach(str -> {
 System.out.println(str);
 });
 System.out.println("使用::遍历");
 // 3.使用::遍历
 list.forEach(System.out::println);
 // 下面的方法和上面等价,使用的是函数式编程
 Consumer<String> methodParam = System.out::println; //方法参数
 list.forEach(x -> methodParam.accept(x));//方法执行accept
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值