【发布时间】:2018-05-02 08:37:45
【问题描述】:
既然Consumer/Supplier/Predicate/UnaryOperator只是Function的一个特例,那我该如何用Function代替这些接口呢?
T -> 函数 -> R
T -> 消费者 -> null
null -> 供应商 -> T
T -> 谓词 -> 布尔值
T -> UnaryOperator -> T
null & boolean 只是 T 的一个特例,所以我写了两个 case 用 Function 来代替 Predicate 和 UnaryOperator。
例如:
private static void replacePredicate() {
Function<String, Boolean> func = x -> x.startsWith("a");
Predicate<String> pre = x -> x.startsWith("a");
System.out.println(func.apply("ape"));
System.out.println(pre.test("ape"));
}
private static void replaceUnaryOperator() {
Function<Integer, Integer> func = x -> x * 2;
UnaryOperator<Integer> uo = x -> x * 2;
System.out.println(func.apply(6));
System.out.println(uo.apply(6));
}
但是我如何使用 Function 来替换 Consumer 或 Suppler?比如我想替换Consumer,但是Function<String, null> func = x -> System.out.println(x);这样的代码是非法的。
任何建议将不胜感激~
【问题讨论】:
-
你为什么要这么做?
-
我不会在生产环境编码的时候使用Function来代替java.util.function中的任何其他函数,因为使用特定函数而不是Function会更方便。但是,通过找到这些函数的本质,我想我可以更好地理解这些函数,并在实践中更好地使用它们。 :D