Java之函数式编程:lambda表达式及函数式接口

面向对象语法有一个非常大的局限性:结构必须非常完整
要想使用函数式编程有一个前提:接口必须只有一个方法,如果有两个方法,则无法使用函数式编程。如果现在某 个接口就是为了函数式编程而生的,最好在定义时就让其只能够定义一个方法,所以有了一个新的注解:
@FunctionalInterface

当行语句语法:
(参数) -> 单行语句 ;
多行语句语法:
(参数) -> {} ;
具体实例如下:

@FunctionalInterface
 interface IUtil2<R>{
     R convert();

}
public class TextMethodRef {
    public static void main(String[] args) {
        String str = "HELLO";
        IUtil2<String> iUtil2 = ()->{
          return str.toLowerCase();//如果现在你的表达式里只有一行进行数据的返回,
          //那么直接使用语句即可,可以不使用return。
        };
        System.out.println(iUtil2.convert());
    }
}

只有一行语句进行数据的返回时可以不用return直接使用语句。

@FunctionalInterface
 interface IUtil2<R>{
     R convert();
}
public class TextMethodRef {
    public static void main(String[] args) {
        String str = "HELLO";
        IUtil2<String> iUtil2 = ()->str.toLowerCase();
        System.out.println(iUtil2.convert());
    }
}

内建函数式接口

Lamdba的核心在于:函数式接口。而函数式接口的核心:只有一个方法。
java.util.function 实际上函数式编程分为以下四种接口:

  1. 功能型函数式接口:public interface Function<T, R> R apply(T t);
import java.util.function.Function;
public class TextMethodRef{
    public static void main(String[] args) {
        Function<Integer,String>fun = String::valueOf;
        System.out.println(fun.apply(1000));
    }
}
  1. 供给型函数式接口: public interface Supplier T get();
  2. 消费型函数式接口:public interface Consumer void accept(T t);
  3. 断言型接口:public interface Predicate boolean test(T t);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值