java8 - 使用Function接口替换Consumer或Supplier

pup*_*lpg 0 lambda java-8

由于Consumer/Supplier/Predicate/UnaryOperator只是Function的一个特例,我如何用Function替换这些interfacces?

T - >功能 - > R.

T - > Consumer - > null

null - >供应商 - > T.

T - >谓词 - >布尔值

T - > UnaryOperator - > T.

null和boolean只是T的一个特例.所以我用函数来编写两个案例来替换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));
}
Run Code Online (Sandbox Code Playgroud)

但是我如何使用Function来替换Consumer或Suppler呢?例如,我想替换Consumer,但代码Function<String, null> func = x -> System.out.println(x);是非法的.

任何建议将不胜感激〜

JB *_*zet 10

A Consumer<T>可以被视为一个Function<T, Void>.A Supplier<T>可以被视为一个Function<Void, T>.您必须从作为函数编写的使用者中返回null,并将(并忽略)作为函数编写的供应商的Void作为参数.

但不确定我是否明白了这一点.