我想了解定义及其示例。
@FunctionalInterface public class Supplier<T> {
public T get();
}
它的用法是
Supplier<LocalDate> s1 = LocalDate::now;
Supplier<LocalDate> s2 = () -> LocalDate.now();
LocalDate d1 = s1.get();
LocalDate d2 = s2.get();
在此,我的理解是now
是工厂方法,由s1
和s2
引用。他们的类型是Supplier<LocalDate>
。我从类型 LocalDate::now
返回LocalDate
类型。
@FunctionalInterface public class Consumer<T> {
void accept(T t);
}
用法,
Consumer<String> c1 = System.out::println;
Consumer<String> c2 = x -> System.out.println(x);
println
是使用String的方法,不返回任何内容。
最后,
@FunctionalInterface public class Predicate<T> {
boolean test(T t);
}
@FunctionalInterface public class BiPredicate<T, U> {
boolean test(T t, U u);
}
他们的用法,
Predicate<String> p1 = String::isEmpty;
Predicate<String> p2 = x -> x.isEmpty();
BiPredicate<String, String> b1 = String::startsWith;
BiPredicate<String, String> b2 = (string, prefix) -> string.startsWith(prefix);
我的问题是Predicate
有一个方法声明返回boolean
并且没有传递任何内容。不是吗?在菱形运算符中左上角的上述两个示例中,存在返回类型或传递类型。因此,isEmpty
声明没有传递类型,boolean
用于返回。同一行为适用于BiPredicate
startsWith
仅采用String
的一个参数类型,返回布尔值。它是如何工作的?因为我认为它应该与Predicate
合作而不是BiPredicate
。但是,在这种情况下,isEmpty
不应与Predicate
一起使用,但有效。我有点困惑。你会解释一下吗?