本内容取自官方示例,并加以小测试使用
1、函数接口说明
函数式接口的定义:
- 有一个抽象方法的普通接口就是函数式接口(静态与默认方法不算),默认继承object,覆盖父类方法也不算;
- 任何函数式接口都可以使用lambda表达式替换
- 这个注解可存在可不存在,有定义多于一个方法时存在则出错
@FunctionalInterface
interface Fun {
void foo();
//void wait();出错
}
2、Predicate接口
用于判断的接口(直接引用函数、表达式)
public static void testPredicate() {
Predicate<String> predicate = (s) -> s.length() > 0;
predicate.test("foo"); // true
predicate.negate().test("foo"); // false
boolean flag = false; //判断布尔值变量
Predicate<Boolean> nonNull = Objects::nonNull;
Predicate<Boolean> isNull = Objects::isNull;
log(nonNull.test(flag));//true
Person pp = new Person("abc,", "efg");
Predicate<String> isEmpty = String::isEmpty;
log(isEmpty.test(pp.firstName));//false
Predicate<String> isNotEmpty = isEmpty.negate();
Predicate<Person> isEqual = e -> "abc".equals(e.firstName);
log("对象值判断:" + isEqual.test(new Person("abc", "efg")));//true
}
3、Function接口
接收一个参数并返回一个结果,并提供一些其他函数可以使用的附加信息
public static void testFunction() {
// Functions
Function<String, Integer> toInteger = Integer::valueOf;
Function<String, String> backToString = toInteger.andThen(String::valueOf);
log(backToString.apply("123")); // "123"
Function<String, String> toFun1 = Lambda3::funTest1;
Function<String, String> toFun2 = Lambda3::funTest2;
log(toFun1.apply("mmo"));
//compose 函数先执行参数,然后执行调用者,而 andThen 先执行调用者,然后再执行参数。
Function<String, String> toFun3 = toFun1.andThen(toFun2);
log(toFun3.apply("xxmmo"));//test2 fun -->test fun -->xxmmo
}
public static String funTest1(String val) {
return "test fun -->" + val;
}
public static String funTest2(String val) {
return "test2 fun -->" + val;
}
4、Supplier接口
提供者接口简单使用,返回任意类型值,与Function区别是没有参数
//每次调用get()方法的时候才会创建对象。并且每次调用创建的对象都不一样;
public static void testSupplier() {
// Suppliers
Supplier<Person> personSupplier = Person::new;
log(personSupplier.get());// new Person
log(personSupplier.get());
Supplier<String> strTest1 = String::new;
log(strTest1.get());//""
}
5、Consumer、Comparator等接口
其他额外几个接口的使用
public static void testOther() throws Exception{
// Consumers:定义一个参数,对其进行(消费)处理,处理的方式可以是任意操作.
Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);//赋值函数
greeter.accept(new Person("Luke", "Skywalker"));//调用
// Comparators:比较
Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);
Person p1 = new Person("John", "Doe");
Person p2 = new Person("Alice", "Wonderland");
comparator.compare(p1, p2); // > 0
comparator.reversed().compare(p1, p2); // < 0
// Runnables
Runnable runnable = () -> System.out.println(UUID.randomUUID());//相当于编写run方法
runnable.run();
// Callables
Callable<UUID> callable = UUID::randomUUID;
callable.call();
}
6、简单调用
public static void main(String[] args) throws Exception {
testPredicate();
testFunction();
testSupplier();
testOther();
}
public static void log(Object val) {
System.out.println(val);
}
更多请参考:
官方