1 概述
上一篇中我们对lambda表达式有了初步的认识,下面我们继续介绍什么是lambda表达式。并从真是例子出发进行学习。
2 什么是lambda表达式
- Lambda 表达式的基础语法:
Java8中引入了一个新的操作符 “->” 该操作符称为箭头操作符或 Lambda 操作符,箭头操作符将 Lambda 表达式拆分成两部分:
左侧:Lambda 表达式的参数列表
右侧:Lambda 表达式中所需执行的功能, 即 Lambda 体
语法格式一:无参数,无返回值
() -> System.out.println("Hello Lambda!");
语法格式二:有一个参数,并且无返回值
(x) -> System.out.println(x)
语法格式三:若只有一个参数,小括号可以省略不写
x -> System.out.println(x)
语法格式四:有两个以上的参数,有返回值,并且 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编译器通过上下文推断出,数据类型,即“类型推断”
(Integer x, Integer y) -> Integer.compare(x, y);
3 Lambda 表达式需要“函数式接口”的支持
函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解 @FunctionalInterface 修饰
可以检查是否是函数式接口。下面通过实例进行进一步学习。
- 线程的创建
public void createThread(){
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("java8之前:开启一个线程");
}
};
runnable.run();
System.out.println("-----------------------");
Runnable runnable1 = () -> System.out.println("lambda表达式:开启一个线程");
runnable1.run();
}
可以看到使用lambda表达式创建线程更加方便快捷,和上面的语法格式1相同,无参,我返回值。那么为什么可以这样呢? 我们通过源码去解读
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
从源码中我们可以看出使用了@FunctionalInterface
注解,并且Rnuuable是一个接口包含一个run()
方法,无参数,无返回值,正好和语法结构1对应。相信大家应该有一定的认识了吧。
2. Comparator的使用
public void test2(){
Comparator<Integer> comparator = (x,y)-> Integer.compare(x,y);
TreeSet<Integer> set = new TreeSet<>();
set.add(5);
set.add(7);
set.add(1);
set.forEach(System.out::println);
}
可以看到这次是传递两个参数x,y返回一个Integer类型的参数,任然通过源码去查看:
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
}
//截取部分
通过源码我们可以更加清晰的看出lambda表达式的写法,其中compare方法传递两个参数,具有一个返回值,正好和上面对应。
相信大家看到这里应该很清楚了吧,lambda表达式到底是怎么一会事了吧。下面我们通过自定义一个接口去做一个练习。
练习:对一个数进行运算
- 自定义接口
@FunctionalInterface
public interface MyFunction {
public Integer getValue(Integer number);
}
- 实现数字运算
@Test
public void test3(){
Integer num = operation(10, (x) -> x * x);
System.out.println(num);
System.out.println(operation(20, (y) -> y + 20));
}
public Integer operation(Integer num, MyFunction mf){
return mf.getValue(num);
}
```