Lambda表达式

Lambda表达式
语法格式一:无参数,无返回值

() -> System.out.println("");
// 例如:
Runnable r1 = () -> System.out.println("");
r1.run();

语法格式二:只有一个参数(注:参数的小括号可以不写),无返回值

Consumer<String> con  = (x) -> System.out.println(x);
con.accept("");

语法格式三:有两个或以上的参数,有返回值,并且Lambda体中有多条语句

Comparator<Integer> com = (x, y) -> {
	System.out.println("函数式接口");
	return Integer.compare(x, y); 
};

语法格式五:当Lambda体中只有一条语句,return和大括号都可以不写

Comparator<Integer> com = (x, y) -> Integer.compare(x, y);

语法格式六:Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器可以通过上下文推断出数据类型,即“类型推断”。

小案例:

// 需求:对一个数进行运算
@Test
public void test() {
	Integer num = operation(100, (x) -> x * x);
	System.out.println(num);
}

public Integer operation(Integer num, MyFun mFun) {
	return mFun.getValue(num);
}

@FunctionalInterface
public interface MyFun {
	public Integer getValue(Integer num);
}

目前来看,该方法有一个缺点:就是每次要使用lambda表达式的时候,都需要建一个接口,这样有点麻烦。
所以jdk8内置了4个接口类专门用于lambda表达式的使用:

Consumer<T>:消费型接口
void accept(T t);

Supplier<T>:供给型接口
T get();

Function<T, R>:函数型接口
R apply(T t);

Predicate<T>:断言型接口(用于做判断)
boolean test(T t);

一、方法引用
若Lambda体中的内容有方法已经实现了,可以使用“方法引用”(可以理解为,方法引用是Lambda表达式的另外一种表现形式)
主要有三种:

  1. 对象::实例方法名
  2. 类名::静态方法名
  3. 类名::实例方法名
// 第一种
// 注:emp对象调用的getAge方法的参数列表和返回值必须要和Supplier的抽象方法的一致
Supplier<Integer> sup = emp::getAge;

// 第二种
// 原本写法
// Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
// 简化写法
Comparator<Integer> com = Integer::compare;

// 第三种
// 原始写法
BiPredicate<String, String> bPredicate = (x, y) -> x.equals(y);
// 简化写法
BiPredicate<String, String> bPredicate2 = String::equals;

二、构造器引用
格式:Classname::new
注意:需要调用的构造器的参数列表要与函数式接口中抽象方法的参数列表保持一致

三、数组引用
格式:type::new;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值