Consumer
Supplier
Function
Predicate
@Test
public void test1(){
consumerLambda(100.0,x-> System.out.println("consume $"+x));
}
/**
* consumer 消费型接口
*/
public void consumerLambda(double money, Consumer<Double> con){
con.accept(money);
}
@Test
public void test2(){
System.out.println(supplyLambda(10,()->(int) (Math.random()*100))); ;
}
/**
* Supplier 供给型接口 在Stream()中的Map中使用
*/
public List<Integer> supplyLambda(int num, Supplier<Integer>sup){
List<Integer> list = new ArrayList<>();
for (int i=0;i<num;i++){
list.add(sup.get());
}
return list;
}
@Test
public void test3(){
System.out.println(FunctionLambda("hello lambda", String::toUpperCase));
}
/**
* Function 函数型接口 在Stream()中的Map中使用,例如获取对象集合的某个熟悉object.getAge()
*/
public String FunctionLambda(String str, Function<String,String>fun){
return fun.apply(str);
}
@Test
public void test4(){
System.out.println(PredicateLambda(Arrays.asList("fewf","fgreg","f","g","fe","oq","gfewgr"), x->x.length()>2));
}
/**
* Predicate 断言型接口 在Stream()中的Filter中使用
*/
public List<String> PredicateLambda(List<String>str, Predicate<String> pre){
return str.stream().filter(pre).collect(Collectors.toList());
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vKLcJVLV-1669908007778)(/Users/lannisite/Downloads/iShot_2022-12-01_14.53.18.png)]
方法引用:若Lambda体中的内容已经有其他方法实现了,我们可以使用“方法引用”。
主要有三种语法格式:
对象::实例方法名
Consumer<String>con = x -> System.out.println(x);
// println 存在实例方法
PrintStream ps = System.out;
// 注意这里,println的括号都可以省略不写,因为只有方法名
con = ps::println;
类名::静态方法名
Comparator<Integer> com = Integer::compare;
类名::实例方法名
BiPredicate<String ,String> bp = (x,y) -> x.equals(y);
bp = String::equals;
实例方法与类方法区别:是否使用static修饰,即是否需要创建实例才可以使用的方法。
构造器引用:
格式:ClassName::new
// 无参构造器
Supplier<Employee> sup = () ->new Employee();
Supplier<Employee> sup2 = Employee::new;
// 一参构造器
Function<String,Employee> fun = (x) -> new Employee(x);
Function<String,Employee> fun2 = Employee::new;
// 至于它会选择哪个构造器,根据参数去匹配
注意:需要调用的构造器的参数列表要与函数式接口中抽象方法的参数列表保持一致
数组引用:
Type::new
Function<Integer,String[]> fun = x -> new String[x];
Function<Integer,String[]> fun2 = String[]::new;