文章目录
Lambda
规则
1,语法格式
语法格式1:无参数,无返回值
() -> System.out.println(“hello”)语法格式2:有一个参数,无返回值,小括号可以省略不写
a -> System.out.println(a);语法格式3:多个参数 ,Lambda体中有多条语句
Comparator com = (x, y) -> {
System.out.println(“aaaa”);
return Integer.compare(x, y);
};语法格式4:有返回值,但是只有一条语句
Comparator com1 = (x,y)->Integer.compare(x, y);语法格式5:参数列表的参数类型可以省略不写
Comparator com1 = (Integer x, Integer y)->Integer.compare(x, y);可以 @FunctionalInterface注解帮我们检查一个接口是不是 函数式接口
2,内置的函数式接口
Consumer: 消费性接口
void accept(T t);Supplier: 供给型接口
T get();Function<T,R>: 函数型接口
R apply(T t);Predicate: 断言型接口
boolean test(T t);
方法引用,构造器引用,数组引用(见例子)
1,方法引用
//方法引用,若lambda体中的内容有方法已经实现了,我们可以使用方法引用。
//注意: 1,lambda体中调用方法的参数列表与返回值类型,要与函数式接口中方法的参数列表和返回值一致才行 // 1,对象::实例方法名
Consumer<String> con = (x)->System.out.println(x);
Consumer<String> con1 = System.out::println;
Supplier<String> su = employee::getName;
//2,类::静态方法名
Comparator<Integer> com = Integer::compare;
//3,类::实例方法名
BiPredicate<String, String> bp = (x,y)->x.equals(y);
//第一个参数时方法的调用者,第二个参数是方法的参数
BiPredicate<String, String> bp1 = String::equals;
2,构造器引用
//构造器引用
//ClassName::new //自动匹配对应的构造器
Supplier<Employee> su = Employee::new; //对应的无参
EmployeeConstructor ec = Employee::new; //对应的多参
interface EmployeeConstructor{
Employee get(String name, int age, double salary);
}
3,数组引用
//数组引用
//type::new
Function<Integer, String[]> fun = (x)-> new String[x];
Function<Integer, String[]> fun2 = String[]::new;
Stream编程
规则
/*
* stream操作步骤
* 1,创建流
* 通过Collection提供的stream()或者paralelStream()
* 通过Arrays.stream(array)
* 通过Stream类中的静态方法 Stream.of("aa","bb","cc")
* 创建无限流
* //迭代
* Stream.iterate(0, x->x+2)
* //生成
* Stream.generate(Math::random)
* 2,中间操作
* 会生成新流
* 2.1 筛选与切片
* filter : 从流中筛选符合条件的对象生成新流
* limit:从流中找到需要的数据前面几个值
* skip: 跳过前n个