闽公网安备 35020302035485号
Lambda可以使用在函数式接口上(仅有一个抽象方法的接口)。由于接口默认法的存在,所以包含多个默认方法但仅有一个抽象方法的接口依然是函数式接口,可以使用注解@FunctionalInterface标注(非必须)。使用函数式接口,可以将代码封在接口里作为参数传递到其他方法,这样业务逻辑就可以外置为参数,灵活性扩展性更高了,再配合Lambda可以大大简化代码。
// 堆代码 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、方法引用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、函数复合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));