java8 - 使用Function接口替换Consumer或Supplier [英] java8 - use Function interface to replace Consumer or Supplier
问题描述
由于Consumer / Supplier / Predicate / UnaryOperator只是Function的一个特例,我如何用Function替换这些界面?
Since that Consumer/Supplier/Predicate/UnaryOperator is just a special case of Function, how can I replace these interfacces with Function?
T - > Function - > R
T -> Function -> R
T - >消费者 - > null
T -> Consumer -> null
null - >供应商 - > T
null -> Supplier -> T
T - > Predicate - > boolean
T -> Predicate -> boolean
T - > UnaryOperator - > T
T -> UnaryOperator -> T
null& boolean只是T的一个特例。所以我用函数代替谓词和UnaryOperator写了两个案例。
null & boolean is just a special case for T. So I write two cases using Function to replace Predicate and 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);
是非法的。
But how could I use Function to replace Consumer or Suppler? For example, I want to replace Consumer, but code like Function<String, null> func = x -> System.out.println(x);
is illegal.
任何建议都将非常感谢〜
Any suggestion will be greatly appreciated~
推荐答案
消费者< T>
可以被视为功能< T,Void> ;
。 供应商< T>
可以被视为功能< Void,T>
。您必须从作为函数编写的消费者中返回null,并从供应商处获取(并忽略)作为函数的Void作为参数。
A Consumer<T>
can be viewed as a Function<T, Void>
. A Supplier<T>
can be viewed as a Function<Void, T>
. You'll have to return null from your consumer written as a function, and take (and ignore) a Void as argument from your supplier written as a function.
不确定不过,我明白了这一点。
Not sure I get the point of this, though.
这篇关于java8 - 使用Function接口替换Consumer或Supplier的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!