java8 - use Function interface to replace Consumer

2019-06-09 02:37发布

问题:

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 -> Consumer -> null

null -> Supplier -> T

T -> Predicate -> boolean

T -> UnaryOperator -> T

null & boolean is just a special case for T. So I write two cases using Function to replace Predicate and UnaryOperator.

For example:

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));
}

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~

回答1:

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.



标签: lambda java-8