Java内置四大核心函数式接口
-
Consumer<T> 消费型接口
- void accept( T t);
-
Supplier<T> 供给型接口, 可在Stream()中的Map中使用
- T get( );
-
Function<T,R> 函数型接口, 可在Stream()中的Map中使用, 将对象集合转变为对象某个熟悉的集合
- R apply(T t);
-
Predicate<T> 断定型接口,可在Stream()中的Filter中使用
- boolean test(T t);
@Test
public void test1(){
consumerLambda(100.0,x-> System.out.println("consume $"+x));
}
/**
* consumer<T> 消费型接口
*/
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<T> 供给型接口 在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<T,R> 函数型接口 在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<T> 断言型接口 在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体中的内容已经有其他方法实现了,我们可以使用“方法引用”。
- 可以理解为方法引用是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修饰,即是否需要创建实例才可以使用的方法。
-
注意:
- Lambda体中调用方法的参数列表与返回值类型,要与函数式接口中抽象方法的函数列表和返回值类型保持一致。
-
构造器引用:
-
格式: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;
-