介绍
Lambda 是一个匿名函数,可以把 Lambda 表达式理解为是一段可以传递的代码(将代码像数据一样进行传递)。使用它可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使 Java 的语言表达能力得到了提升。
语法格式
(o1, o2) -> o1-o2;
(...):Lambda形参列表,若为空则()->{};->: Lambda操作符,箭头操作符...:Lambda体,编写系列表达式
例子
()->{ System.out.println("Lambda") }(String str)->{ System.out.println(str) }(str)->{ System.out.println(str) }str->{ System.out.println(str) }- (i, j) -> {
- System.out.println(i-j);
- return i-j;
- }
-
(i,j) -> retrun i-j自定义函数式接口
@FunctionalInterface 用于检查该接口是否为函数式接口
- @FunctionalInterface
- public interface MyInterface {
- void method();
- }
-
使用
- ((MyInterface) () -> System.out.println("123")).method();
-
Java内置函数式接口
位于java.util.function包下
主要四大接口

其他接口

使用
- @Test
- public void t2() {
- t2t("1", str -> {
- System.out.println(str + "23");
- });
- }
-
- public void t2t(String str, Consumer<String> consumer) {
- consumer.accept(str);
- }
-
- @Test
- public void t3() {
- List<String> list = new ArrayList<>();
- list.add("好的");
- list.add("好哒");
- list.add("你的");
- list.add("你哒");
- list.add("我的");
- System.out.println(t3t(list, s -> s.contains("的")));
- }
-
- //过滤字符串
- public List<String> t3t(List<String> list, Predicate<String> predicate) {
- List<String> filterList = new ArrayList<>();
- for(String s : list){
- if(predicate.test(s)){
- filterList.add(s);
- }
- }
- return filterList;
- }
-
方法引用
方法引用可以看做是 Lambda 表达式深层次的表达。换句话说,方法引用就是 Lambda 表达式,也就是函数式接口的一个实例,通过方法的名字来指向一个方法。
什么时候可以使用方法引用?
使用格式
使用操作符::分割方法名和类或对象
对象::实例方法名- Consumer<String> c1 = str -> System.out.println(str);
-
- PrintStream out = System.out;
- Consumer<String> c2 = out::println;
-
- String str = "123";
- Supplier
s1 = () -> str.length(); -
- Supplier
s2 = str::length; -
类::静态方法名- Comparator<Integer> c1 = (t1, t2) -> Integer.compare(t1, t2);
- Comparator<Integer> c2 = Integer::compare;
-
- Function<Double, Long> f1 = d -> Math.round(d);
- Function<Double, Long> f2 = Math::round;
-
类::实例方法名- Comparator<Integer> c1 = (t1, t2) -> t1.compareTo(t2);
- Comparator<Integer> c2 = Integer::compareTo;
-
- BiPredicate<String, String> b1 = (s1, s2) -> s1.equals(s2);
- BiPredicate<String, String> b2 = String::equals;
-
- Function<String, Integer> f1 = str -> str.length();
- Function<String,Integer> f2 = String::length;
-
构造器和数组引用
和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。抽象方法的返回值类型即为构造器所属的类的类型
使用格式
方法引用:className ::new 数组引用:数组的类型 [] :: new
- //构造器引用
- Supplier<String> s1 = () -> new String();
- Supplier<String> s2 = String::new; //调用空参构造函数
- Function
String> f1 = str -> new String(str); - Function
String> f2 = String::new; //调用有参构造函数 -
- BiFunction
String> b1 = (bytes,charset) -> new String(bytes,charset); - BiFunction
String> b2 = String::new; -
- //数组引用
- Function
String[]> f3 = length -> new String[length]; - Function
String[]> f4 = Stri