JDK 1.8 新增加的函数接口(java.util.function包下):
- 暂只列出了以下 内置的四大基础函数式接口(实际上还有很多…):
序号 | 接口 | 描述 |
---|
1 | Consumer< T> | 消费型:接受一个输入参数(T ),无返回结果 |
2 | Supplier< T> | 供给型:无参数,返回一个结果(R ) |
3 | Function< T,R> | 函数型:接受一个输入参数(T ),返回一个结果(R ) |
4 | Predicate< T> | 断言型:接受一个输入参数(T ),返回一个布尔值结果(R ) |
@SpringBootTest
public class FunctionTest {
@Test
public void test(){
System.out.println("供给型接口(Supplier): " + FunctionTest.getPhone(() -> "111"));
System.out.println("------------------------------------------------------" + "\n");
System.out.println("消费型接口(Consumer): ");
FunctionTest.setPhone(System.out::println);
System.out.println("------------------------------------------------------" + "\n");
System.out.println("函数型接口(Function) -> 写法1: Lambda表达式: " + FunctionTest.dealPhone("222", (a) -> Arrays.asList("ABC")));
System.out.println("函数型接口(Function) -> 写法2: 实例方法: " + FunctionTest.dealPhone("222", FunctionTest::apply));
System.out.println("------------------------------------------------------" + "\n");
System.out.println("断言型接口(Predicate): " + FunctionTest.isPhone("12311112222", (a) -> PhoneUtil.isPhone(a)));
}
private static String getPhone(Supplier<String> supplier) {
return supplier.get();
}
private static void setPhone(Consumer<String> consumer) {
consumer.accept(new FunctionTest().toString());
}
private static List<String> dealPhone(String phone, Function<String, List<String>> function) {
return function.apply(phone);
}
private static Boolean isPhone(String phone, Predicate<String> predicate) {
return predicate.test(phone);
}
private static List<String> apply(String a) {
return Arrays.asList("ABC");
}
}
- 结果截图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ed4213955739508f73b7005a27076de3.png)