• JAVA中Lambda表达式的使用
  • 发布于 2个月前
  • 351 热度
    0 评论
  • 黄月英
  • 0 粉丝 57 篇博客
  •   
本文简要快速说明Lambda表达式的使用,比较简单,基本内容如下:

1、函数式接口

Lambda可以使用在函数式接口上(仅有一个抽象方法的接口)。由于接口默认法的存在,所以包含多个默认方法但仅有一个抽象方法的接口依然是函数式接口,可以使用注解@FunctionalInterface标注(非必须)。使用函数式接口,可以将代码封在接口里作为参数传递到其他方法,这样业务逻辑就可以外置为参数,灵活性扩展性更高了,再配合Lambda可以大大简化代码。


2、常用接口
Predicate:根据入参返回boolean
Consumer:根据入参执行操作无返回
Function:根据入参执行操作并返回
其他函数式接口基本类似,只是函数描述符可能不同,比如Runnable没有入参也没有返回值。
// 堆代码 duidaima.com
List<String> list = Arrays.asList("star", "moon", "sun");
// filter中predicate
list.stream().filter(s -> s.length() > 3).collect(Collectors.toList());
//forEach中consumer
list.stream().forEach(s -> System.out.println(s));
//map中function
list.stream().map(s -> s.toUpperCase()).collect(Collectors.toList());
//无入参无返回
new Thread((()->System.out.println("lambda") )).start();
3、方法引用
如果在Lambda中只是调用了一个方法,那么可以简写为方法引用。可以使用静态方法的方法引用(Integer::parseInt),可以引用实例对象的方法(任意类型的方法或上下文实例对象的方法),也可以是构造函数引用。
List<String> list = Arrays.asList("star", "moon", "sun");
list.stream().forEach(System.out::println);
list.stream().map(String::toUpperCase).collect(Collectors.toList());
Supplier<List> supplier = ArrayList::new;
List s = supplier.get();
4、函数复合
应该称作Lambda表达式复合,这里使用函数Function说明,其他函数式接口类似。函数提供了andThen和compose两个默认方法,均返回Function实例,所以多个函数可以进行链式调用完成多个功能。
Function<Integer,Integer> f1 = x -> x + x;
Function<Integer,Integer> f2 = x -> x * x;
Function<Integer, Integer> t = f1.andThen(f2);
//100
System.out.println(t.apply(5));
Function<Integer, Integer> c = f1.compose(f2);
//50
System.out.println(c.apply(5));

用户评论